0% found this document useful (0 votes)
226 views20 pages

Real-Time Encapsulation Interview Questions and Answers

The document discusses real-time encapsulation interview questions and answers. It provides definitions and examples of encapsulation, the benefits of encapsulation, how to achieve encapsulation in Java with an example class, and the differences between abstraction and encapsulation. It also explains getter and setter methods, provides a real-world example of encapsulation, discusses encapsulation in design patterns, and how variables can be accessed using getter and setter methods.

Uploaded by

Mahesh Giri
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
226 views20 pages

Real-Time Encapsulation Interview Questions and Answers

The document discusses real-time encapsulation interview questions and answers. It provides definitions and examples of encapsulation, the benefits of encapsulation, how to achieve encapsulation in Java with an example class, and the differences between abstraction and encapsulation. It also explains getter and setter methods, provides a real-world example of encapsulation, discusses encapsulation in design patterns, and how variables can be accessed using getter and setter methods.

Uploaded by

Mahesh Giri
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 20

Real-time Encapsulation Interview Questions and Answers

In this tutorial, we will discuss Real-time Encapsulation Interview Questions and Answers with some
practical examples. We will try to present answers in very easy ways so that you could not get any trouble to
understand and remember the answers. 

1. What is Encapsulation? Why is it called Data hiding?

Ans: Encapsulation is a technique of making the fields private in the class and providing the access to the fields via
the public method. 
If a field is declared private in the class then it cannot be accessed by anyone outside the class and hides the fields
within the class. Therefore, Encapsulation is also called data hiding.

2. What are the features of Encapsulation?

Ans: Encapsulation means combining the data of our application and its manipulation in one place.
Encapsulation allows the state of an object to be accessed and modified through behavior. It reduces the coupling
of modules and increases the cohesion inside them.

3. What are the advantages of Encapsulation?

Ans: There are following advantages of Encapsulation:

➝ An encapsulated code is more flexible and easy to change with new requirements.
➝ Encapsulation prevents the other classes to access the private fields.

➝ Encapsulation allows modifying implemented code without breaking others code who have implemented the
code.

➝ It keeps the data and codes safe from external inheritance.

➝ If you don't define setter method in the class then the fields can be made read-only.

➝ If you don't define getter method in the class then the fields can be made write-only.

➝ Encapsulation also helps to write the immutable class in java which is the good choice in multithreading.

4. What are the main benefits of using encapsulation in Java?

Ans: The main benefits of using encapsulation are:

➝ The main benefit of encapsulation is the ability to modify the implemented code without breaking the others
code who have implemented the code. 
➝ It also provides us with maintainability, flexibility, and extensibility to our code. 

➝ The fields of a class can be made read-only or write-only.

➝ A class can have total control over what is stored in its fields.

5. How to achieve encapsulation in Java? give an example.

Ans: To achieve the encapsulation in Java:

➝ Declare the variable of the class as private.

➝ Provide public setter and getter methods to modify the values of variables.

Example: 

public class EncapsulationTest private String name; private String idNum; private int age; public int
getAge(){ return age; } public String getName(){ return name; } public String getIdNum(){ return idNum; }
public void setAge( int newAge){ age = newAge; } public void setName(String newName){ name = newName; }
public void setIdNum( String newId){ idNum = newId; } }

6. What is the difference between Abstraction and Encapsulation?

Ans: Difference between Abstraction and Encapsulation:


➝ Abstraction solves the problem at design level whereas 
    Encapsulation solves the problem at the implementation level.
➝ Abstraction is implemented in Java using Interface and Abstract class whereas Encapsulation is implemented
using private and protected access modifiers.
➝ Abstraction is used to hide the unwanted data and giving relevant data whereas Encapsulation is used for
hiding data and code in a single unit to prevent the access from outside.
➝ The real-time example of Abstraction is TV Remote Button whereas 
    The real-time example of Encapsulation is medical medicine.

7. What are the getter and setter methods in Java?

Ans: In Java, setter method is a method which is used for updating the values of a variable. This method is also
known as mutator method. 

Getter method is a method which is used to retrieve the value of a variable or return the value of the private
member variable. This method is also known as an accessor method.

8. Give a real-time example of encapsulation in Java?


Ans: Suppose you have an account in the bank. If your balance variable is defined as a public variable in the bank
software then your account balance will be known public then, in this case, anyone can know your account
balance. So do you like it? Obviously No. 

   So for making your account safe, they declare balance variable as private so that anyone cannot see your
account balance and the person who have to see account balance then they will have to access private members
only through methods defined inside that class and this method will ask your account holder name or user Id, or
password for authentication. 
Thus, security is achieved by utilizing the concept of data hiding. This is called Encapsulation.

9. Explain design pattern based on encapsulation in java?


Ans: Many design pattern  Java uses encapsulation technique and one of them is Factory pattern which is used to
create the objects. Factory pattern is a better choice in creating the object of those classes whose creation logic can
vary. It is also used for creating different implementations of the same interface. 
 'BorderFactory class' of JDK is a good example of encapsulation in Java which creates different types of 'border'
and encapsulates creation logic of border.

10. How can the variable of the EncapsulationTest be accessed by using getter and setter methods?
Ans: The public setXXX() and getXXX() methods are access points of the instance variable of EncapsulationTest
class. Basically, these methods are known as getter and setter methods. Therefore, any class that wants to access
variable should access them through these getters and setters. 

What is the difference between primitive and non primitive


data types in Java?
Primitives are the most basic kinds of data types and they driectly contain values. There are eight
primitive types in total:

 byte
 short
 int
 long
 char
 boolean
 float
 double
Non primitive data types are called reference types in Java and they refer to an object. They are
created by the programmer and are not defined by Java like primitives are. A reference type
references a memory location where the data is stored rather than directly containing a value.

Primitive Data Type,

A primitive data type is one that fits the base architecture of the underlying computer such as int,
float, and pointer, and all of the variations, thereof such as char short long unsigned float double and
etc, are primitive data type.

Primitive data are only single values, they have not special capabilities.

The examples of Primitive data types are given byte, short, int, long, float, double, char etc.

Primitive Data types are predefined in Java. They are named by a Keyword.


➝ Primitive data types are those data types whose variables can store only one value at a time. 

Non- Primitive Data type,


A non-primitive data type is something else such as an array structure or class is known as the non-
primitive data type.

The data type that are derived from primary data types are known as non-primitive data type.
The non-primitive data types are used to store the group of values.

Examples of non-primitive data type.

Array, structure, union, link list, stacks, queue etc.

10 Main Differences Between Overloading & Overriding in Java


In this tutorial, we will discuss 10 main differences between the method overloading and method overriding in
Java. What is the difference between overloading and overriding in Java? is the most valuable, very important, and
repeatedly asked question in any technical interview. Interviewer always hopes three to four differences from your
answer. So, let's start with a basic definition.

METHOD OVERLOADING VS METHOD OVERRIDING IN JAVA

There are the following differences between method overloading and method overriding in Java. They are as
follows:
1. Definition: 
a. When a class has more than one method having the same name but different in parameters, it is called method
overloading in Java.
b. When the method of superclass is overridden in subclass to provide more specific implementation, it is
calledmethod overriding in Java.

2. Argument types: 
a. Argument type must be different (at least order) in overloading.
b. In overriding, argument type must be the same (including order).

3. Method signature: 
a. The signature of the overloaded method must be different.
b. The signature of the overriding method must be the same.

4. Return type:
a. In method overloading, the return type can be the same or different.
b. In method overriding, the return type must be the same until Java 1.4 version but Java 1.5 onwards, method
overriding can be done by changing the covariant return type. 
5. Class: 
a. Method overloading is generally performed in the same class.
b. Method overriding is performed in two classes through inheritance (Is-A relationship).

6. Private/static/final method: 
a. Private, static, and final method can be overloaded in Java.
b. Overriding concept is not applicable to private, static, and final method. Private, static, and final method can be
overridden in Java.

7. Access modifiers: 
a. In overloading, access modifiers can be anything or different.
b. In overriding, subclass method's access modifier must be same or higher than superclass method access
modifier i.e we cannot reduce the visibility subclass method while overriding.

8. Throws clause: 
a. Exception thrown can be anything in the overloading concept.
b. In case of method overriding, if child class method throws any checked exception compulsory parent class
method should throw the same checked exception are its parent otherwise we will get compile time error but there is
no restriction for an unchecked exception.

9. Method resolution: 
a. Method resolution in overloading always takes care by the compiler based on reference type.
b. Method resolution in overriding always takes care by JVM based on runtime object.

10. Polymorphism: 
a. Method overloading is also known as compile-time polymorphism, static polymorphism, or early binding.
b. Method overriding is also known as runtime polymorphism, dynamic polymorphism, or late binding.

Can we define constructors in an abstract class?


An abstract class can have a constructor but it cannot be instantiated. If you do not define your own
constructor compiler will give a default constructor to the Abstract class.

why we use a constructor in abstract class in java?


A constructor is used in the abstract method because some time we need to initialize variables in
subclass like below code.

 class Main extends User {


 String education;

 Main(String education, String name, int age) {
 super(name, age);
 this.education = education;
 }

 public static void main(String[] args) {
 Main obj = new Main("MCA", "rahul", 22);
 System.out.println(obj.education + " " + obj.name + " " + obj.age);
 }

 @Override
 public void msg() {
 // TODO Auto-generated method stub
 // write your code....

 }
 }

 abstract class User {
 String name;
 int age;

 User(String name, int age) {
 this.name = name;
 this.age = age;
 }

 public abstract void msg();

 }

Can we define an abstract class as a final class?


My answer is direct no because as abstraction says you are going implement the methods, and as you
know if we define as a final we can’t change anything. They are also opposite of each other, abstract
keyword enforces to extend a class, for using it, on the other hand, final keyword prevents a class
from being extended.

Is it necessary for an abstract class to have an abstract method?


No, it’s not necessary because we can define concrete and non-concreate method in abstract class.

Difference between abstract class and interface in Java.


An abstract class can contain abstract and non-abstract method but in interface only abstract method
its true before java 8 version now we can define. please read in detail.
Can we define the main class as an abstract class?
Yes, the abstract class can contain the main method.

 abstract class Main {



 public static void main(String[] args) {
 System.out.println("hello codebun");
 }
 }

Can we declare abstract methods as private?


No, If abstract methods are allowed to be private, then they will not be inherited to subclass.
Can we put a static method in interfaces?
No, we cannot put static methods in interfaces because all the methods are by default public
and abstract in the interface and we cannot use abstract and static keywords together.

What is default keyword in an interface?


By the help of default keyword, we can keep non-abstract method in java interface i.e with
method body{}. This is the new feature of JAVA 8.

Syntax of default keyword :

interface Test
{
default void show()
{
-----
-----
}
}

What is marker or tagged interface?


Marker interface is an interface that has no data member and method like Serializable,
Cloneable, etc.

Can we Overload static methods in Java

July 27, 2015 by javainterviewpoint Leave a Comment

Yes, you can overload a static method in Java. Java Method Overloading is one of the feature in


OOPs concept which allows you to have two or more methods with same method
name with difference in the parameters in other words, we can also call this phenomena as Compile
time polymorphism.

Overloading of static method

Lets see in the below example we have a OverloadExample class which has two static disp()methods
which differs in the number of parameters.

package com.javainterviewpoint;

public class OverloadExample


{
public static void disp()
{
System.out.println("disp() method without parameter called");
}
public static void disp(String name)
{
System.out.println("disp() method with parameter called : "+name);
}
public static void main(String args[])
{
//Calling disp() method which has no parameter
OverloadExample.disp();

//Calling disp() method which has one parameter


OverloadExample.disp("JavaInterviewPoint");
}
}
when we run the above code we will be getting the below output.

disp() method without parameter called


disp() method with parameter called : JavaInterviewPoint
Overloading of methods which differs in static keyword

We cannot overload two methods which differs in static keyword but has the same method


signature. When we try to do so we will be getting ” Cannot make a static reference to the non-static
method “ error.

package com.javainterviewpoint;

public class OverloadExample


{
public void disp()
{
System.out.println("Non static disp() method called");
}

public static void disp()


{
System.out.println("static disp() method called121");
}

public static void main(String args[])


{
//Calling the disp() method
OverloadExample.disp();

}
}
Running the above code will lead to the below exception

Exception in thread "main" java.lang.Error: Unresolved compilation problem:


Cannot make a static reference to the non-static method disp() from the type
OverloadExample
Can we Override static methods in Java

July 27, 2015 by javainterviewpoint Leave a Comment

No, We cannot Override a static method in Java. Unlike Overloading of static methodwe cannot do


overriding. When we declare a method with same signature and static in both Parent and Child class
then it is not considered as Method Overriding as there will not be any Run-time
Polymorphismhappening.
When the Child class also has defined thesame static method like Parent class, then the method in
the Child class hides the method in the Parent class. In the below code we can see that we are having
a static display() method in both Parent and Child class.

package com.javainterviewpoint;

import java.io.IOException;

class Parent
{
public static void display()
{
System.out.println("Welcome to Parent Class");
}
}
public class Child extends Parent
{
public static void display()
{
System.out.println("Welcome to Child class");
}
public static void main(String args[])
{
//Assign Child class object to Parent reference
Parent pc = new Child();
pc.display();
}
}
Output :

Welcome to Parent Class


As per overriding in Java, the display()method of the Child class should be called, since it is
a static method overriding will not happen here and hence the Parent class display() method is called
here.

1. What is static keyword in Java?

Static is a Non Access Modifier. Static can be applied to variable, method, nested class and
initialization blocks (static block).

2. What is a static variable ?

 A Static variable gets memory allocated only once during the time of class loading.
 All the instance of the class share the same copy of the variable, a static variable can be accessed
directly by calling “<<ClassName>>.<<VariableName>>” without need to create instance for the class.
 value of a static variable will be common for all instances

public class StaticVariableExample


{
static int a =10;
public static void main(String args[]){
StaticVariableExample s1 = new StaticVariableExample();
StaticVariableExample s2 = new StaticVariableExample();
System.out.println("s1.a value :"+s1.a);
System.out.println("s2.a value :"+s2.a);
//Change s1 a value alone
s1.a=20;
System.out.println("s1.a value :"+s1.a);
System.out.println("s2.a value :"+s2.a);
}
}
Output will be
s1.a value :10
s2.a value :10
s1.a value :20
s2.a value :20

 Local variables cannot be assigned as static it will throw compile time error “illegal start of expression”,
as the memory cannot be assigned during class load.

3. What is a static method ?

 A static method belongs to class rather than object. It can be called directly by using the
classname “<<ClassName>>.<<MethodName>>”
 A static method can access static varaibles directly and it cannot access non-staticvariables and can only
call a static method directly and it cannot call a non-static method from it.
 Only the main() method which is static will be called by the JVM automatically, Not all the static method
will be called automatically.

4. Can a static block exist without a main() method ?

Yes. You can have static block alone in the class without a main method.

5. Can we Overload static methods in Java

Yes, you can overload a static method in Java. Read More..

6. Can we Override static methods in Java

No, you cannot override a static method in Java as there will not be any Run-time
Polymorphism happening. Read More..

7. Why main() method is declared as static ?

If our main() method is not declared as static then the JVM has to create object first and call which
causes the problem of having extra memory allocation.

8. What is a static block ?

 A static block, is a block of code inside a Java class that will be executed when a class is first loaded in to
the JVM. Mostly the static block will be used for initializing the variables.
 Static block will be called only one while loading and it cannot have any return type, or any keywords
(this or super).
class test
{
int val;
static{
val = 100;
}
}
9.  Can we have multiple static blocks in our code ?

Yes, we can have more than one static block in our code. It will be executed in the same order it is
written.

10. What is a static class ?

 In Java only nested classes are allowed to be declared as static, a top level class cannot be declared as
static.
 Even though static classes are nested inside a class, they doesn’t need the reference of the outer class
they act like outer class only. Read More..

11. Can constructors be static in Java ?

In general a static method means that “The Method belong to class and not to any particular object”
but a constructor is always invoked with respect to an object, so it makes no sense for a constructor to
be static.

12. Why abstract methodcannot be static in Java ?

Suppose when you have a concrete method in a abstract class then that method can be static.
Suppose we have a class like below

public class AbstractTest


{
static void disp()
{
System.out.println("disp of static method");
}
}
Then the disp() can be access by “AbstractTest.disp()”
However, for the same reason cannot be applied when you declare a static method to be abstract.
Since static method can be called directly, making it abstract would make it possible to call
an undefined method which is of no use, hence it is not allowed.

13. Can Interface in Java have static methods in it ?

No, Interface cannot have static methods in it because all methods are implicitly abstract. This is why
an interface cannot have a static method.

14. Can abstract class have static variable in it ?

Yes, an abstract class can have static variables in it.


15. non-static method cannot be referenced from a static context ?

public class Test


{
/** Non Static main method with String[] args**/
public static void main(String[] args)
{
welcome();
}

void welcome()
{
System.out.println("Welcom to JavaInterviewPoint");
}
}
The welcome() method which we tried calling is an instance-level method, we do not have
an instance to call it . static methods belong to the class, non-static methods belong to instances of
the class and hence it throws the error ” non-static method cannot be referenced from a static context “.

Can we use this and super in static context?


No, because this and super belongs to objects.

Can we write static public void main(String [] args)?

 Yes we can define main method like static public void main(String[] args){}
  Order of modifiers we can change.

1) What is an exception?

Exception is an abnormal condition which occurs during the execution of a program and disrupts
normal flow of the program. This exception must be handled properly. If it is not handled, program
will be terminated abruptly.

2) How the exceptions are handled in java? OR Explain exception handling mechanism in
java?

Exceptions in java are handled using try, catch and finally blocks.

try block : The code or set of statements which are to be monitored for exception are kept in this
block.

catch block : This block catches the exceptions occurred in the try block.

finally block : This block is always executed whether exception is occurred in the try block or not and
occurred exception is caught in the catch block or not.
3) What is the difference between error and exception in java?

Errors are mainly caused by the environment in which an application is running. For example,
OutOfMemoryError happens when JVM runs out of memory. Where as exceptions are mainly caused
by the application itself. For example, NullPointerException occurs when an application tries to access
null object.

Click here to see more about Error Vs Exception in java.


4) Can we keep other statements in between try, catch and finally blocks?

No. We shouldn’t write any other statements in between try, catch and finally blocks. They form a
one unit.

1
try
2
{
3
    // Statements to be monitored for exceptions
4
}
5
  
6 //You can't keep statements here

7   

8 catch(Exception ex)

9 {

10     //Cathcing the exceptions here

11 }

  
12
//You can't keep statements here
13
  
14
finally
15
{
16
    // This block is always executed
17
}
18

5) Can we write only try block without catch and finally blocks?

No, It shows compilation error. The try block must be followed by either catch or finally block. You
can remove either catch block or finally block but not both.
6) There are three statements in a try block – statement1, statement2 and statement3.
After that there is a catch block to catch the exceptions occurred in the try block. Assume
that exception has occurred in statement2. Does statement3 get executed or not?

No. Once a try block throws an exception, remaining statements will not be executed. control comes
directly to catch block.

7) What is unreachable catch block error?

When you are keeping multiple catch blocks, the order of catch blocks must be from most specific to
most general ones. i.e sub classes of Exception must come first and super classes later. If you keep
super classes first and sub classes later, compiler will show unreachable catch block error.

1 public class ExceptionHandling

2 {

    public static void main(String[] args)


3
    {
4
        try
5
        {
6
            int i = Integer.parseInt("abc");   //This statement throws NumberFormatExceptio
7
        }
8
  
9         catch(Exception ex)

10         {

11             System.out.println("This block handles all exception types");

12         }

13   

14         catch(NumberFormatException ex)

        {
15
            //Compile time error
16
            //This block becomes unreachable as
17
            //exception is already caught by above catch block
18
        }
19
    }
20 }

21
22

8) Explain the hierarchy of exceptions in java?


Click here to see the hierarchy of exceptions in java.
9) What are run time exceptions in java. Give example?

The exceptions which occur at run time are called as run time exceptions. These exceptions are
unknown to compiler. All sub classes of java.lang.RunTimeException and java.lang.Error are run time
exceptions. These exceptions are unchecked type of exceptions. For example,
NumberFormatException, NullPointerException, ClassCastException,
ArrayIndexOutOfBoundException, StackOverflowError etc.

10) What is OutOfMemoryError in java?

OutOfMemoryError is the sub class of java.lang.Error which occurs when JVM runs out of memory.

11) what are checked and unchecked exceptions in java?

Checked exceptions are the exceptions which are known to compiler. These exceptions are checked
at compile time only. Hence the name checked exceptions. These exceptions are also called compile
time exceptions. Because, these exceptions will be known during compile time.

Unchecked exceptions are those exceptions which are not at all known to compiler. These exceptions
occur only at run time. These exceptions are also called as run time exceptions. All sub classes of
java.lang.RunTimeException and java.lang.Error are unchecked exceptions.

Click here to see more about checked and unchecked exceptions.


12) What is the difference between ClassNotFoundException and NoClassDefFoundError
in java?
Click here to see the differences between ClassNotFoundException and NoClassDefFoundError in
java.
13) Can we keep the statements after finally block If the control is returning from the
finally block itself?

No, it gives unreachable code error. Because, control is returning from the finally block itself.
Compiler will not see the statements after it. That’s why it shows unreachable code error.

14) Does finally block get executed If either try or catch blocks are returning the control?

Yes, finally block will be always executed no matter whether try or catch blocks are returning the
control or not.

15) Can we throw an exception manually? If yes, how?

Yes, we can throw an exception manually using throw keyword. Syntax for throwing an exception
manually is

throw InstanceOfThrowableType;

Below example shows how to use throw keyword to throw an exception manually.
1
try
2 {

3     NumberFormatException ex = new NumberFormatException();    //Creating an object to Numb

4   

5     throw ex;        //throwing NumberFormatException object explicitly using throw keyword

6 }

7 catch(NumberFormatException ex)

{
8
    System.out.println("explicitly thrown NumberFormatException object will be caught here"
9
}
10

Click here to see more about throw keyword.


16) What is Re-throwing an exception in java?

Exceptions raised in the try block are handled in the catch block. If it is unable to handle that
exception, it can re-throw that exception using throw keyword. It is called re-throwing an exception.

1
try
2
{
3     String s = null;

4     System.out.println(s.length());   //This statement throws NullPointerException

5 }

6 catch(NullPointerException ex)

{
7
    System.out.println("NullPointerException is caught here");
8
  
9
    throw ex;     //Re-throwing NullPointerException
10
}
11

17) What is the use of throws keyword in java?


Click here to see the uses of throws keyword in java.
18) Why it is always recommended that clean up operations like closing the DB resources
to keep inside a finally block?

Because finally block is always executed whether exceptions are raised in the try block or not and
raised exceptions are caught in the catch block or not. By keeping the clean up operations in finally
block, you will ensure that those operations will be always executed irrespective of whether exception
is occurred or not.

19) What is the difference between final, finally and finalize in java?
Click here to see the differences between final, finally and finalize in java.
20) How do you create customized exceptions in java?
Click here to see about customized exceptions in java.
21) What is ClassCastException in java?

ClassCastException is a RunTimeException which occurs when JVM unable to cast an object of one
type to another type.

22) What is the difference between throw, throws and throwable in java?
Click here to see the differences between throw, throws and throwable in java.
23) What is StackOverflowError in java?

StackOverflowError is an error which is thrown by the JVM when stack overflows.

24) Can we override a super class method which is throwing an unchecked exception


with checked exception in the sub class?

No. If a super class method is throwing an unchecked exception, then it can be overridden in the sub
class with same exception or any other unchecked exceptions but can not be overridden with
checked exceptions.

25) What are chained exceptions in java?


Click here to see about chained exceptions in java.
26) Which class is the super class for all types of errors and exceptions in java?

java.lang.Throwable is the super class for all types of errors and exceptions in java.

27) What are the legal combinations of try, catch and finally blocks?

1)

1
try
2 {

3     //try block

4 }

5 catch(Exception ex)

6 {

    //catch block
7
}
8
2)

1
try
2 {

3     //try block

4 }

5 finally

6 {

    //finally block
7
}
8

3)

1
try
2
{
3
    //try block
4 }

5 catch(Exception ex)

6 {

7     //catch block

8 }

finally
9
{
10
    //finally block
11
}
12

28) What is the use of printStackTrace() method?

printStackTrace() method is used to print the detailed information about the exception occurred.

29) Give some examples to checked exceptions?

ClassNotFoundException, SQLException, IOException

30) Give some examples to unchecked exceptions?


NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException

Q5. What is the difference between a checked and an unchecked


exception?
A checked exception must be handled within a try-catch block or declared in a throws clause;
whereas an unchecked exception is not required to be handled nor declared.
Checked and unchecked exceptions are also known as compile-time and runtime exceptions
respectively.
All exceptions are checked exceptions, except those indicated by Error, RuntimeException, and
their subclasses.

Q13. What are the rules we need to follow when overriding a method
that throws an exception?
When the parent class method doesn’t throw any exceptions, the child class method can’t throw any
checked exception, but it may throw any unchecked.

When the parent class method throws one or more checked exceptions, the child class method can
throw any unchecked exception; all, none or a subset of the declared checked exceptions, and even
a greater number of these as long as they have the same scope or narrower.

When the parent class method has a throws clause with an unchecked exception, the child class
method can throw none or any number of unchecked exceptions, even though they are not related.

You might also like