TOPICS: EXCEPTION HANDLING & ACCESS MODIFIERS
Exception Handling
Some of your programs when executed may have terminated unexpectedly with
runtime errors. The errors could have occurred because an array index reference
was out of range, or an attempt was made to divide an integer by zero, or there
was insufficient computer memory and so on. Such an error situation that is
unexpected in the program execution and causes it to terminate unexpectedly is
called an exception. As a programmer, you should anticipate exceptions in your
program that could lead to unpredictable results and handle the exceptions.
Java provides an exception handling mechanism so that a program is able to
deal with exceptions, and continue executing or terminate gracefully. The basic
idea in exception handling is to
Denote an exception block – Identify areas in the code where errors can occur
Catch the exception – Receive the error information
Handle the exception – Take corrective action to recover from the error Java
provides the following keywords to handle an exception:
try – A try block surrounds the part of the code that can generate exception(s).
catch – The catch blocks follow a try block. A catch block contains the exception
handler – specific code that is executed when the exception occurs. Multiple
catch blocks following a try block can handle different types of exceptions.
The structure of a try-catch statement block for exception handling is as below:
try {
// Part of the program where an exception might occur
}
catch (exceptiontype1 argument1) {
// Handle exception of the exceptiontype1
}
catch (exceptiontype2 argument2) {
// Handle exception of the exceptiontype2
}
finally {
//Code to be executed when the try block exits
}
The try block is examined during execution to detect any exceptions that may be
thrown by any statements or any calls to methods within the block. If an
exception is thrown, an exception object is created and thrown. The program
execution stops at that point and control enters the catch block whose argument
matches the type of the exception object thrown. If a match is found the
statements in that catch block are executed for handling the exception. If no
exception is thrown during execution of the statements in the try block, the catch
clauses that follow the try block are not executed. Execution continues at the
statement after the last catch clause. The optional finally block is always
executed when the try block exits. This means the finally block is executed
whether an exception occurs or not.
Example:
public class Exceptionhandling {
public static void main(String args[]) {
int d,a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed."+a);
}
catch (ArithmeticException e) {
// catch divide-by-zero error
System.out.println("Division by zero.");
}
finally
{
System.out.println("After catch statement.");
}
}
}
ACCESS MODIFIERS
Access Modifiers In Java
The access modifiers also determine which data members (methods or fields) of a class
can be accessed by other data members of classes or packages etc. To ensure
encapsulation and reusability, these access modifiers are an integral part of object-oriented
programming.
Modifiers in Java are of two types:
#1) Access Modifiers
Access modifiers in Java allow us to set the scope or accessibility or visibility of a data
member be it a field, constructor, class, or method.
#2) Non-access Modifiers
Java also provides non-access specifies that are used with classes, variables, methods,
constructors, etc. The non-access specifies/modifiers define the behavior of the entities to
the JVM.
Some of the non-access specifies/modifiers in Java are:
static
final
abstract
transient
volatile
synchronized
native
We have covered static, synchronized, and volatile keywords in our earlier tutorials. We will
cover the other non-access modifiers in our future tutorials as they are beyond the scope of
this tutorial.
Types of Access Modifiers In Java
Java provides four types of access modifiers that we can use with classes and other
entities.
These are:
#1) Default: Whenever a specific access level is not specified, then it is assumed to be
‘default’. The scope of the default level is within the package.
#2) Public: This is the most common access level and whenever the public access
modifiers is used with an entity, that particular entity is accessible throughout from within or
outside the class, within or outside the package, etc.
#3) Protected: The protected access level has a scope that is within the package. A
protected entity is also accessible outside the package through inherited class or child
class.
#4) Private: When an entity is private, then this entity cannot be accessed outside the
class. A private entity can only be accessible from within the class.
We can summarize the access modifiers in the following table.
Access Modifiers Inside Class Inside Package Outside package subclass Outside pack
Private Yes No No No
Default Yes Yes No No
Protected Yes Yes Yes No
Public Yes Yes Yes Yes
A class or a method or a data field specified as ‘public’ is accessible from any class or
package in the Java program. The public entity is accessible within the package as well as
outside the package. In general, public access modifier is a modifier that does not restrict
the entity at all.
Public Access Modifier
class A
{
public void display()
{
System.out.println("SoftwareTestingHelp!!");
}
}
class Main
{
public static void main(String args[])
{
A obj = new A ();
obj.display();
}
}
Output:
Private Access Modifier
The ‘private’ access modifier is the one that has the lowest accessibility level. The methods
and fields that are declared as private are not accessible outside the class. They are
accessible only within the class which has these private entities as its members.
Note that the private entities are not even visible to the subclasses of the class. A private
access modifier ensures encapsulation in Java.
Some points to be noted regarding the Private Access Modifier.
1. Private access modifier cannot be used for classes and interfaces.
2. The scope of private entities (methods and variables) is limited to the class in which
they are declared.
3. A class with a private constructor cannot create an object of the class from any other
place like the main method.
Frequently Asked Questions
Q #1) How many Access Modifiers are there in Java?
Answer: Java provides four modifiers i.e. default, public, protected, and private.
Q #2) What are Access Modifiers and Non- Access Modifiers in Java?
Answer: Access modifiers define the visibility or scope of a program entity like a class or a
method or a variable or a constructor. Non-access modifiers define the behavior of an
entity. For example, a synchronized method or block indicates that it can operate in a
multithreading environment, a final variable indicates that it is a constant.
Q #3) Why are Access Specifiers important?
Answer: Modifiers specify which class can access which other classes or methods or
variables. Using access specifiers we can limit the access of various classes, methods,
constructors, and variables and also ensure encapsulation and reusability of Java entities.
Q #4) Which Modifiers are not used for the class?
Answer: Protected and Private modifiers are not used for a class.
Q #5) What are Non-access Modifiers?
Answer: Modifiers that define the behavior of entities like class, method, or variables with
which they are associated are non-access modifiers. As the name suggests they do not
specify the access. Java provides various non-access modifiers like static, final,
synchronized, volatile, abstract, etc.
More On Visibility Modifiers
Java provides many modifiers to access the variable, methods, and constructors.
There are 4 types of access variables in Java:
1. Private
2. Public
3. Default
4. Protected
#1) Private
If a variable is declared as private, then it can be accessed within the class. This variable
won’t be available outside the class. So, the outside members cannot access the private
members.
Note: Classes cannot be private.
#2) Public
Methods/variables with public modifiers can be accessed by all the other classes in the
project.
#3) Protected
If a variable is declared as protected, then it can be accessed within the same package
classes and sub-class of any other packages.
Note: Protected access modifier cannot be used for class.
#4) Default Access Modifier
If a variable/method is defined without any access modifier keyword, then that will have a
default modifier access.
Access Modifiers Visibility
Public Visible to All classes.
Protected Visible to classes with in the package and the subclasses of other package.
No Access Modifier (Default) Visible to the classes with the package
private Visible with in the class. It is not accessible outside the class.