Packages, Access Specifiers, Exception Handling

The package is a group of related classes and interfaces. The main objective is code reusability. Any class once after derived successfully can be accessed by importing the respective package. package can be created with the help of keyword package.

Syntax:

package <pkg_name>
class classname{
//Data Members and Methods
}

Packages are two different types

  1. Predefined packages
  2. User defined packages

The predefined packages are Java and Javax . The package consists of many sub packages.

Depending on the requirement of the user the respective package and the sub package will be imported into the user program using the keyword “import”.

Syntax:

import mainpkg.subpkg.classname

Incase of the user defined packages, the package definition and its path will be defined by the user.

Example

└── root
└── mypack
└── MyPackageClass.java

To create a package, use the package keyword:

MyPackageClass.java

package mypack;
class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my package!");
}
}

Save the file as MyPackageClass.java, and compile it:

C:\Users\Your Name>javac MyPackageClass.java

Then compile the package:

C:\Users\Your Name>javac -d . MyPackageClass.java

This forces the compiler to create the “mypack” package.

The -d keyword specifies the destination for where to save the class file. You can use any directory name, like c:/user (windows), or, if you want to keep the package within the same directory, you can use the dot sign ".", like in the example above.

Note: The package name should be written in lower case to avoid conflict with class names.

When we compiled the package in the example above, a new folder was created, called “mypack”.

To run the MyPackageClass.java file, write the following:

C:\Users\Your Name>java mypack.MyPackageClass

The output will be:

This is my package!

Access Specifiers and their accessibility

In Java private, public, protected, default are the access specifiers. They define the level of access for each data member and the method and the class.

The following table demonstrates the level of access in Java program

Inner Classes

A class that is defined inside another class is an inner class.

class OuterClass{
datamembers;
class InnerClass{
datamembers;
methods;
}
outer class methods;
}

With the help of an inner class we can have access to the data and methods of outer class directly. However, we can limit the scope of innerclass with in the outer class itself.

Local Classes

An inner class whose definition is given inside the method of a class is nothng but a local class.

class OuterClass{
datamembers;
public returntype method(){
class InnerClass{
datamembers;
methods;
}
}
outer class methods;
}

Here in the class definition of the inner class is confined to the method in which it is defined.

Exception Handling

An abnormal solution i.e., raised during the program execution is nothing but exception. Every exception may lead to abnormal termination of program which may cause inconsistency in software reliability. Such exceptions may be handled by Java through a mechanism with which the program will be successfully executed even if an exception is raised.

When executing Java code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things. When an error occurs, Java will normally stop and generate an error message. The technical term for this is: Java will throw an exception (throw an error).

Normally, the run time errors may be due to the external failures like memory errors, device errors and power failures. However, exception handling is not applicable for such errors. It can only be done for the runtime errors that are caused/raised due to the elements in the program.

Java supports the exception handling extensive through a predefined class library.

Every exception is a class in Java. Throwable is a super class for all Java exceptions. The main objective is to increase software reliability. No software should be terminated in the middle during the program execution for the trivial exceptions.

Exception handling is done by means of the following elements

  1. try block
  2. catch block
  3. finally block
  4. throw
  5. throws

Java try and catch

The try statement allows you to define a block of code to be tested for errors while it is being executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

The try and catch keywords come in pairs:

Syntax

try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}

Consider the following example:

This will generate an error, because myNumbers[10] does not exist.

public class Main {
public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}
}

The output will be something like this:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 at Main.main(Main.java:4)

If an error occurs, we can use try...catch to catch the error and execute some code to handle it:

Example

public class Main {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}

The output will be:

Something went wrong.

Finally

The finally statement lets you execute code, after try...catch, regardless of the result:

Example

public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
}
}

The output will be:

Something went wrong.
The 'try catch' is finished.

The throw keyword

The throw statement allows you to create a custom error. The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc:

Example

Throw an exception if age is below 18 (print “Access denied”). If age is 18 or older, print “Access granted”:

public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}
}

The output will be:

Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be at least 18 years old.
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)

If age was 20, you would not get an exception:

Example

checkAge(20);
The output will be:
Access granted - You are old enough!

--

--