Java Interview questions(1)
Java Interview questions(1)
Explain the FailFast iterator and FailSafe iterator along with examples for
each.
An Exception is an Event that interrupts the normal flow of the program and
requires special processing. During the execution of a program, errors and
unplanned occurrences can be dealt with by using the Java Exception Handling
mechanism. Below are some reasons why Exceptions occur in Java:
Device failure
Loss of Network Connection
Code Errors
Opening an Unavailable file
Invalid User Input
Physical Limitations (out of disk memory)
Exceptions -> Recover from exceptions by either using a try-catch block or throwing
exceptions back to the caller.
It includes both checked as well as unchecked types that occur.
The program is mostly responsible for causing exceptions.
All exceptions occur at runtime but checked exceptions are known to the compiler
while unchecked are not.
They are defined in java.lang.Exception package
Examples: Checked Exceptions: SQLException, IOException Unchecked Exceptions:
ArrayIndexOutOfBoundException, NullPointerException, ArithmeticException.
All exception and error types in Java are subclasses of the class throwable, which
is the base class of the hierarchy. This class is then used for exceptional
conditions that user programs should catch. NullPointerException is an example of
such an exception. Another branch, error is used by the Java run-time system to
indicate errors having to do with the JRE. StackOverflowError is an example of one
of such error.
Runtime Exceptions are exceptions that occur during the execution of a code, as
opposed to compile-time exceptions that occur during compilation. Runtime
exceptions are unchecked exceptions, as they aren’t accounted for by the JVM.
7. What is NullPointerException?
It is a type of run-time exception that is thrown when the program attempts to use
an object reference that has a null value. The main use of NullPointerException is
to indicate that no value is assigned to a reference variable, also it is used for
implementing data structures like linked lists and trees.
Checked Exception:
Checked Exceptions are the exceptions that are checked during compile time of a
program. In a program, if some code within a method throws a checked exception,
then the method must either handle the exception or must specify the exception
using the throws keyword.
Checked exceptions are of two types:
- Fully checked exceptions: all its child classes are also checked, like
IOException, and InterruptedException.
- Partially checked exceptions: some of its child classes are unchecked, like an
Exception.
Unchecked Exception:
Unchecked are the exceptions that are not checked at compile time of a program.
Exceptions under Error and RuntimeException classes are unchecked exceptions,
everything else under throwable is checked.