30+ Java Exception Handling Interview Questions And Answers

pramodbablad

  • April 14, 2023
  • Exception Handling , Java Interview Questions

11 Comments

Java exception handling is one of the favorite topic of the many interviewers to test the candidate’s basic Java skills. In this post, I have collected some of the likely Java exception handling interview questions which you may face in your technical interview. I hope it will help you.

30+ Most Asked Java Exception Handling Interview Questions And Answers

1) What is an exception?

Exception is an abnormal condition which occurs during the execution of a program and disrupts normal flow of a 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.

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 block or finally block.

Note : From Java 7, with the introduction of try-with resources blocks, we can write only try block without catch and finally blocks provided resources must be AutoCloseable.

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, statement3 is not executed. 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 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.

8) Explain the hierarchy of exceptions in Java?

Java Exception Handling Interview Questions And Answers

Click here to see more about 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 itself.

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 more about ClassNotFoundException Vs NoClassDefFoundError in Java.

13) Can we keep the statements after finally block If the finally block is returning the control?

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.

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.

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

throws keyword is used to specify the exceptions that a particular method can throw. The syntax for using throws keyword is,

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 more details about 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 is 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 more about 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 with 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?

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

31) Do you know try-with-resources blocks? Why do we use them? When they are introduced?

Try-with-resources blocks are introduced from Java 7 to auto-close the resources like File I/O streams, Database connection, network connection etc… used in the try block. You need not to close the resources explicitly in your code. Try-with-resources implicitly closes all the resources used in the try block.

32) What are the benefits of try-with-resources?

The main benefit of try-with-resources is that it avoids resource leaks that could happen if we don’t close the resources properly after they are used. Another benefit of try-with-resources is that it removes redundant statements in the code and thus improves the readability of the code.

33) What are the changes made to exception handling from Java 7?

Multi-catch exceptions and try-with-resources are two major changes made to exception handling from Java 7. Click here to see Java 7 exception handling changes.

34) What are the improvements made to try-with-resources in Java 9?

Click here to see the improvements made to try-with-resources in Java 9.

35) What are the differences between StackOverflowError and OutOfMemoryError In Java?

Also Read :

  • Java Exception Handling Cheat Sheet

Java Exception Handling Quiz

  • Java Strings Interview Questions
  • Java Array Interview Questions
  • Java Inheritance Interview Questions
  • Interview Questions On main()
  • Interview Questions On final keyword
  • 110+ Java Interview Programs
  • 15 Simple but confusing interview questions
  • 40+ Core Java Coding Q&A
  • 25+ simple basic Java interview questions
  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to email a link to a friend (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)
  • Click to share on Telegram (Opens in new window)

Related Posts

Java 8 interview sample coding questions.

  • June 26, 2023

Java Array Interview Questions And Answers

  • April 23, 2023
  • December 13, 2022

What design pattern is used to implement exception handling features in most languages? plz reply..

it is chain of responsibility design pattern

Chain Of Responsibility Pattern

5) Can we write only try block without catch and finally blocks? Yes, From java 7 onwards, if a class implements AutoCloseable interface, then it could be used as an argument in the try section and then it is not compulsory to have catch or finally block. Please refer to the below example. Here Scanner class implements AutoCloseable interface.

public class Test{ public static void main(String[] args) { //After the completion of try block, the scanner object would be auto closed. try(Scanner sc = new Scanner(System.in)){ System.out.println(sc.hashCode()); } } }

5) Yes , In Java 7 with the introduction of try with resources concept , we are able to write try block without catch and finally blocks. The only constraint is the resources which we are declaring as try block parameter must implements Autocloseable interface. A resource is said to be Autocloseable if and only if corresponding class implements java.lang.Autocloseable interface.

consider following example snipped try{ int a = 10/0; // statement 1 }catch(ArithmeticException ae){ // handle code } My question is – exception arise at statement 1 but how java internally identify that exception is ArithmeticException or else ?

When an exception occurs inside a Java method, the method creates an Exception object and passes the Exception object to the JVM (in Java term, the method ” throw ” an Exception ). The Exception object contains the type of the exception, and the state of the program when the exception occurs.

Consider the following code snippet.

void method () { statement1; try { statement2; } catch (Exception e) { //Exception Handling code } statement3; } If statement1, statement2 and statement3 all throw exceptions, catch block can handle exceptions thrown by which statement[s]?

if all statements throws exceptions then program will terminated at statement1. And if statement1 is not throwing any kind of exception then catch block will handle statement2’s exception.

Catch block executes whenever a statement failed to execute in try block, any statement which failed to execute then it will directly throw an exception to catch block and won’t execute next statement.

Site is Awesome!…

Leave a Reply Cancel Reply

Name  *

Email  *

Add Comment

Notify me of follow-up comments by email.

Notify me of new posts by email.

Post Comment

Learn Java practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn java interactively, java introduction.

  • Get Started With Java
  • Your First Java Program
  • Java Comments

Java Fundamentals

  • Java Variables and Literals
  • Java Data Types (Primitive)
  • Java Operators
  • Java Basic Input and Output
  • Java Expressions, Statements and Blocks

Java Flow Control

  • Java if...else Statement
  • Java Ternary Operator
  • Java for Loop
  • Java for-each Loop
  • Java while and do...while Loop
  • Java break Statement
  • Java continue Statement
  • Java switch Statement
  • Java Arrays
  • Java Multidimensional Arrays
  • Java Copy Arrays

Java OOP(I)

  • Java Class and Objects
  • Java Methods
  • Java Method Overloading
  • Java Constructors
  • Java Static Keyword
  • Java Strings
  • Java Access Modifiers
  • Java this Keyword
  • Java final keyword
  • Java Recursion
  • Java instanceof Operator

Java OOP(II)

  • Java Inheritance
  • Java Method Overriding
  • Java Abstract Class and Abstract Methods
  • Java Interface
  • Java Polymorphism
  • Java Encapsulation

Java OOP(III)

  • Java Nested and Inner Class
  • Java Nested Static Class
  • Java Anonymous Class
  • Java Singleton Class
  • Java enum Constructor
  • Java enum Strings
  • Java Reflection
  • Java Package

Java Exception Handling

  • Java Exceptions

Java try...catch

Java throw and throws

Java catch Multiple Exceptions

Java try-with-resources

  • Java Annotations
  • Java Annotation Types
  • Java Logging
  • Java Assertions
  • Java Collections Framework
  • Java Collection Interface
  • Java ArrayList
  • Java Vector
  • Java Stack Class
  • Java Queue Interface
  • Java PriorityQueue
  • Java Deque Interface
  • Java LinkedList
  • Java ArrayDeque
  • Java BlockingQueue
  • Java ArrayBlockingQueue
  • Java LinkedBlockingQueue
  • Java Map Interface
  • Java HashMap
  • Java LinkedHashMap
  • Java WeakHashMap
  • Java EnumMap
  • Java SortedMap Interface
  • Java NavigableMap Interface
  • Java TreeMap
  • Java ConcurrentMap Interface
  • Java ConcurrentHashMap
  • Java Set Interface
  • Java HashSet Class
  • Java EnumSet
  • Java LinkedHashSet
  • Java SortedSet Interface
  • Java NavigableSet Interface
  • Java TreeSet
  • Java Algorithms
  • Java Iterator Interface
  • Java ListIterator Interface

Java I/o Streams

  • Java I/O Streams
  • Java InputStream Class
  • Java OutputStream Class
  • Java FileInputStream Class
  • Java FileOutputStream Class
  • Java ByteArrayInputStream Class
  • Java ByteArrayOutputStream Class
  • Java ObjectInputStream Class
  • Java ObjectOutputStream Class
  • Java BufferedInputStream Class
  • Java BufferedOutputStream Class
  • Java PrintStream Class

Java Reader/Writer

  • Java File Class
  • Java Reader Class
  • Java Writer Class
  • Java InputStreamReader Class
  • Java OutputStreamWriter Class
  • Java FileReader Class
  • Java FileWriter Class
  • Java BufferedReader
  • Java BufferedWriter Class
  • Java StringReader Class
  • Java StringWriter Class
  • Java PrintWriter Class

Additional Topics

  • Java Keywords and Identifiers
  • Java Operator Precedence
  • Java Bitwise and Shift Operators
  • Java Scanner Class
  • Java Type Casting
  • Java Wrapper Class
  • Java autoboxing and unboxing
  • Java Lambda Expressions
  • Java Generics
  • Nested Loop in Java
  • Java Command-Line Arguments

Java Tutorials

In the last tutorial, we learned about Java exceptions . We know that exceptions abnormally terminate the execution of a program.

This is why it is important to handle exceptions. Here's a list of different approaches to handle exceptions in Java.

  • try...catch block
  • finally block
  • throw and throws keyword

1. Java try...catch block

The try-catch block is used to handle exceptions in Java. Here's the syntax of try...catch block:

Here, we have placed the code that might generate an exception inside the try block. Every try block is followed by a catch block.

When an exception occurs, it is caught by the catch block. The catch block cannot be used without the try block.

Example: Exception handling using try...catch

In the example, we are trying to divide a number by 0 . Here, this code generates an exception.

To handle the exception, we have put the code, 5 / 0 inside the try block. Now when an exception occurs, the rest of the code inside the try block is skipped.

The catch block catches the exception and statements inside the catch block is executed.

If none of the statements in the try block generates an exception, the catch block is skipped.

2. Java finally block

In Java, the finally block is always executed no matter whether there is an exception or not.

The finally block is optional. And, for each try block, there can be only one finally block.

The basic syntax of finally block is:

If an exception occurs, the finally block is executed after the try...catch block. Otherwise, it is executed after the try block. For each try block, there can be only one finally block.

Example: Java Exception Handling using finally block

In the above example, we are dividing a number by 0 inside the try block. Here, this code generates an ArithmeticException .

The exception is caught by the catch block. And, then the finally block is executed.

Note : It is a good practice to use the finally block. It is because it can include important cleanup codes like,

  • code that might be accidentally skipped by return, continue or break
  • closing a file or connection

3. Java throw and throws keyword

The Java throw keyword is used to explicitly throw a single exception.

When we throw an exception, the flow of the program moves from the try block to the catch block.

Example: Exception handling using Java throw

In the above example, we are explicitly throwing the ArithmeticException using the throw keyword.

Similarly, the throws keyword is used to declare the type of exceptions that might occur within the method. It is used in the method declaration.

Example: Java throws keyword

When we run this program, if the file test.txt does not exist, FileInputStream throws a FileNotFoundException which extends the IOException class.

The findFile() method specifies that an IOException can be thrown. The main() method calls this method and handles the exception if it is thrown.

If a method does not handle exceptions, the type of exceptions that may occur within it must be specified in the throws clause.

To learn more, visit Java throw and throws .

Table of Contents

  • Introduction
  • Java try...catch block
  • Java finally block
  • Java throw and throws keyword

Sorry about that.

Related Tutorials

Java Tutorial

assignment questions on exception handling in java

How to Nail your next Technical Interview

You may be missing out on a 66.5% salary hike*, nick camilleri, how many years of coding experience do you have, free course on 'sorting algorithms' by omkar deshpande (stanford phd, head of curriculum, ik), help us with your details.

interviewkickstart dark logo

35 Java Exception Handling Interview Questions and Answers

Last updated by Swaminathan Iyer on May 30, 2024 at 05:52 PM | Reading time: 9 minutes

Many interviewers like to test your basic Java skills by asking you about exception handling in Java. And thus, practicing Java exception handling interview questions before your tech interview can help you ace it.

Exception handling ensures that the program's flow does not break when an exception occurs. For example, suppose a program contains many statements, and an exception occurs in the middle of executing some of them. In that case, the statements following the exception will not be executed, and the program will terminate abruptly.

Exception handling is one of the most important topics for a technical interview, so read on to learn about the most frequently asked interview questions on exception handling in Java.

If you are preparing for a tech interview, check out our technical interview checklist , interview questions page, and salary negotiation e-book to get interview-ready!

Having trained over 10,000 software engineers , we know what it takes to crack the toughest tech interviews. Our alums consistently land offers from FAANG+ companies. The highest ever offer received by an IK alum is a whopping $1.267 Million!

At IK, you get the unique opportunity to learn from expert instructors who are hiring managers and tech leads at Google, Facebook, Apple, and other top Silicon Valley tech companies.

Want to nail your next tech interview ? Sign up for our FREE Webinar .

In this article, we’ll cover:

Top Java Interview Questions on Exception Handling

Miscellaneous java interview questions on exception handling, tips to answer java interview questions on exception handling, faqs on java interview questions on exception handling.

If you are willing to kickstart your career with Java, go through the following commonly asked exception handling in Java interview questions and answers:

Q1. How can you handle exceptions in Java?

Exception handling can be performed using:

  • Try: the set of statements or code which requires monitoring for an exception is kept under this block.
  • Catch: this block catches all exceptions that were trapped in the try block.
  • Finally: this block is always performed irrespective of the catching of exceptions in the try or catch block.

Q2. What is the difference between exception and error in Java?

Errors typically happen while an application is running. For instance, Out of Memory Error occurs in case the JVM runs out of memory. On the other hand, exceptions are mainly caused by the application. For instance, Null Pointer Exception happens when an app tries to get through a null object.

Q3. Why do we need exception handling in Java?

If there is no try and catch block while an exception occurs, the program will terminate. Exception handling ensures the smooth running of a program without program termination.

Q4. Name the different types of exceptions in Java

Based on handling by JVM, there are typically two types of exceptions in Java:

  • Checked: Occur during the compilation. Here, the compiler checks whether the exception is handled and throws an error accordingly.
  • Unchecked: Occur during program execution. These are not detectable during the compilation process.

Types of exception handling

In addition, there are two other exceptions based on their definition, namely built-in expectation and user-defined expectations.

Q5. Can we just use try instead of finally and catch blocks?

No, doing so will show a compilation error. Catch or finally block must always accompany try block. We can remove either finally block or catch block, but never both.

Make sure to prepare for the above-mentioned interview questions on exception handling in Java before appearing for your upcoming interview. You can also look at some of the Top Java Programming Interview Questions and Answers . Apart from these, most tier-1 companies tend to ask a few other interview questions on exception handling in Java. They are mentioned in the following section.

Here are a few other important interview questions on exception handling in Java that you must know:

  • Describe the difference between unchecked and checked exceptions in Java.
  • What is the difference between finally, final, and finalize in Java?
  • Define try-with resource. How can you say that it differs from an ordinary try?
  • Define Runtime Exception. Describe it with the help of an example.
  • What is the difference between NoClassDefFoundError and ClassNotFoundException in Java?
  • Can we throw an exception explicitly or manually?
  • Describe the use of the throw keyword.
  • Why should we clean up activities such as I/O resources in the finally block?
  • Describe OutofMemoryError in exception handling.
  • What is the error of  ClassCastException?
  • Is there any difference between throw and throws in exception handling in Java?
  • When should we use the printStackTrace() method?
  • Provide me with some examples of unchecked exceptions.
  • Is it illegal to keep an empty catch?
  • What are the advantages of using exception handling in Java?
  • Can checked exceptions occur at compiled time?
  • What happens if a runtime exception occurs?
  • Describe unreachable catch block error in Java.
  • In which situation will you not be able to execute the finally block?
  • Is it possible to throw a statement inside a static block?
  • Define rethrowing.
  • Define user-defined or custom exceptions in Java.
  • What do you understand by a chained exception?
  • What do you understand about throwables in Java?
  • Mention the methods in the throwable class.
  • Give me some examples of checked exceptions.
  • Define NumberFormatException exception in Java.
  • What do you understand by ArrayIndexOutOfBoundsException?
  • Suppose there is a catch block in tune with a try block with 3 statements - 1, 2, and 3. Now, imagine that the statement is thrown in statement 2. Will there be an execution of statement 3?
  • Define unreachable catch block error.

You may find it overwhelming to answer such technical Java interview questions on exception handling for experienced developers. So, your mantra toward nailing the next tech interview should be to practice, practice, and practice!

You can also practice some Java Interview Questions for Software Developers With 5 Years of Experience . Meanwhile, go through a few tips mentioned below that will help you face the interview questions with utmost confidence during your D-day.

When responding to Java interview questions on exception handling, you must follow these guidelines:

  • Put utmost attention to the question. If you are unsure about the question, simply ask for clarification and then answer.
  • Don't make any assumptions if the interviewer asks you practical interview questions in Java exception handling. Simply answer what you are confident about .
  • Listen to any hint. If your interviewer provides you with any hints, ensure that you don’t miss them. Most importantly, do not ignore the hint.
  • If your interviewer asks you to demonstrate a process, make sure that you lay out all the steps in detail and do not miss out on anything.
  • Finally, try your best to learn all about the company and position you are applying for.

That said, having an in-depth knowledge of these Java interview questions on exception handling will help you during your tech interview prep.

Q1. How many total exceptions are there in Java?

There are three exceptions in Java, including the error, checked exception, and runtime.

Q2. Is Java difficult to learn?

Compared to various other programming languages, Java is fairly easy to learn. That said, to master Java, you will require constant practice.

Q3. What should we direct to try block?

We direct the statements which may cause problems or disruption in an application to the try block.

Q4. Can exception handling resolve the exceptions?

No. Exception handling in Java can only catch the exception and not resolve them.

Q5. What are the five keywords in exception handling in Java?

The five keywords in exception handling in Java are:

Gear Up for Your Next Tech Interview

Are you getting ready for an upcoming Java interview? Register for our technical interview webinar .

At Interview Kickstart , we’ve trained over 10,000 engineers to land lucrative offers at the biggest tech companies. Our instructors, who are FAANG hiring managers, know what it takes to nail tough tech interviews at top technology companies.

Register for our FREE webinar to learn more.

assignment questions on exception handling in java

Recession-proof your Career

Recession-proof your software engineering career.

Attend our free webinar to amp up your career and get the salary you deserve.

Ryan-image

Attend our Free Webinar on How to Nail Your Next Technical Interview

assignment questions on exception handling in java

Zoox Software Engineer Interview Questions to Crack Your Tech Interview

Zoom interview questions, top 40 workday interview questions, how to answer the “why microsoft” interview question, how to answer the “why apple” interview question, how to answer the interview question — "what are your salary expectations", top python scripting interview questions and answers you should practice, complex sql interview questions for interview preparation, rubrik interview questions for software engineers, top advanced sql interview questions and answers, twilio interview questions, ready to enroll, next webinar starts in.

entroll-image

Get  tech interview-ready to navigate a tough job market

  • Designed by 500 FAANG+ experts
  • Live training and mock interviews
  • 17000+ tech professionals trained

Exception Handling in Java: A Complete Guide with Best and Worst Practices

assignment questions on exception handling in java

Handling Exceptions in Java is one of the most basic and fundamental things a developer should know by heart. Sadly, this is often overlooked and the importance of exception handling is underestimated - it's as important as the rest of the code.

In this article, let's go through everything you need to know about exception handling in Java, as well as good and bad practices.

  • What is Exception Handling?

We are surrounded by exception handling in real-life on an everyday basis.

When ordering a product from an online shop - the product may not be available in stock or there might occur a failure in delivery. Such exceptional conditions can be countered by manufacturing another product or sending a new one after the delivery failed.

When building applications - they might run into all kinds of exceptional conditions. Thankfully, being proficient in exception handling, such conditions can be countered by altering the flow of code.

  • Why use Exception Handling?

When building applications, we're usually working in an ideal environment - the file system can provide us with all of the files we request, our Internet connection is stable and the JVM can always provide enough memory for our needs.

Sadly, in reality, the environment is far from ideal - the file cannot be found, the Internet connection breaks from time to time and the JVM can't provide enough memory and we're left with a daunting StackOverflowError .

If we fail to handle such conditions, the whole application will end up in ruins, and all other code becomes obsolete. Therefore, we must be able to write code that can adapt to such situations.

Imagine a company not being able to resolve a simple issue that arose after ordering a product - you don't want your application to work that way.

  • Exception Hierarchy

All of this just begs the question - what are these exceptions in the eyes of Java and the JVM?

Exceptions are, after all, simply Java objects that extend the Throwable interface:

When we talk about exceptional conditions, we are usually referring to one of the three:

  • Checked Exceptions
  • Unchecked Exceptions / Runtime Exceptions

Note : The terms "Runtime" and "Unchecked" are often used interchangeably and refer to the same kind of exceptions.

Checked Exceptions are the exceptions that we can typically foresee and plan ahead in our application. These are also exceptions that the Java Compiler requires us to either handle-or-declare when writing code.

The handle-or-declare rule refers to our responsibility to either declare that a method throws an exception up the call stack - without doing much to prevent it or handle the exception with our own code, which typically leads to the recovery of the program from the exceptional condition.

This is the reason why they're called checked exceptions . The compiler can detect them before runtime, and you're aware of their potential existence while writing code.

  • Unchecked Exceptions

Unchecked Exceptions are the exceptions that typically occur due to human, rather than an environmental error. These exceptions are not checked during compile-time, but at runtime, which is the reason they're also called Runtime Exceptions .

They can often be countered by implementing simple checks before a segment of code that could potentially be used in a way that forms a runtime exception, but more on that later on.

Errors are the most serious exceptional conditions that you can run into. They are often irrecoverable and there's no real way to handle them. The only thing we, as developers, can do is optimize the code in hopes that the errors never occur.

Errors can occur due to human and environmental errors. Creating an infinitely recurring method can lead to a StackOverflowError , or a memory leak can lead to an OutOfMemoryError .

  • How to Handle Exceptions
  • throw and throws

The easiest way to take care of a compiler error when dealing with a checked exception is to simply throw it.

We are required to mark our method signature with a throws clause. A method can add as many exceptions as needed in its throws clause, and can throw them later on in the code, but doesn't have to. This method doesn't require a return statement, even though it defines a return type. This is because it throws an exception by default, which ends the flow of the method abruptly. The return statement, therefore, would be unreachable and cause a compilation error.

Keep in mind that anyone who calls this method also needs to follow the handle-or-declare rule.

When throwing an exception, we can either throw a new exception, like in the preceding example, or a caught exception.

  • try-catch Blocks

A more common approach would be to use a try - catch block to catch and handle the arising exception:

In this example, we "marked" a risky segment of code by encasing it within a try block. This tells the compiler that we're aware of a potential exception and that we're intending to handle it if it arises.

This code tries to read the contents of the file, and if the file is not found, the FileNotFoundException is caught and re-thrown . More on this topic later.

Running this piece of code without a valid URL will result in a thrown exception:

Alternatively, we can try to recover from this condition instead of re-throwing:

Running this piece of code without a valid URL will result in:

  • finally Blocks

Introducing a new kind of block, the finally block executes regardless of what happens in the try block. Even if it ends abruptly by throwing an exception, the finally block will execute.

This was often used to close the resources that were opened in the try block since an arising exception would skip the code closing them:

However, this approach has been frowned upon after the release of Java 7, which introduced a better and cleaner way to close resources, and is currently seen as bad practice.

  • try-with-resources Statement

The previously complex and verbose block can be substituted with:

It's much cleaner and it's obviously simplified by including the declaration within the parentheses of the try block.

Additionally, you can include multiple resources in this block, one after another:

This way, you don't have to concern yourself with closing the resources yourself, as the try-with-resources block ensures that the resources will be closed upon the end of the statement.

  • Multiple catch Blocks

When the code we're writing can throw more than one exception, we can employ several catch blocks to handle them individually:

When the try block incurs an exception, the JVM checks whether the first caught exception is an appropriate one, and if not, goes on until it finds one.

Note : Catching a generic exception will catch all of its subclasses so it's not required to catch them separately.

Catching a FileNotFound exception isn't necessary in this example, because it extends from IOException , but if the need arises, we can catch it before the IOException :

This way, we can handle the more specific exception in a different manner than a more generic one.

Note : When catching multiple exceptions, the Java compiler requires us to place the more specific ones before the more general ones, otherwise they would be unreachable and would result in a compiler error.

  • Union catch Blocks

To reduce boilerplate code, Java 7 also introduced union catch blocks . They allow us to treat multiple exceptions in the same manner and handle their exceptions in a single block:

  • How to throw exceptions

Sometimes, we don't want to handle exceptions. In such cases, we should only concern ourselves with generating them when needed and allowing someone else, calling our method, to handle them appropriately.

  • Throwing a Checked Exception

When something goes wrong, like the number of users currently connecting to our service exceeding the maximum amount for the server to handle seamlessly, we want to throw an exception to indicate an exceptional situation:

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

This code will increase numberOfUsers until it exceeds the maximum recommended amount, after which it will throw an exception. Since this is a checked exception, we have to add the throws clause in the method signature.

To define an exception like this is as easy as writing the following:

  • Throwing an Unchecked Exception

Throwing runtime exceptions usually boils down to validation of input, since they most often occur due to faulty input - either in the form of an IllegalArgumentException , NumberFormatException , ArrayIndexOutOfBoundsException , or a NullPointerException :

Since we're throwing a runtime exception, there's no need to include it in the method signature, like in the example above, but it's often considered good practice to do so, at least for the sake of documentation.

Again, defining a custom runtime exception like this one is as easy as:

  • Re-throwing

Re-throwing an exception was mentioned before so here's a short section to clarify:

Re-throwing refers to the process of throwing an already caught exception, rather than throwing a new one.

Wrapping, on the other hand, refers to the process of wrapping an already caught exception, within another exception:

  • Re-throwing Throwable or _Exception*?

These top-level classes can be caught and re-thrown, but how to do so can vary:

In this case, the method is throwing a NumberFormatException which is a runtime exception. Because of this, we don't have to mark the method signature with either NumberFormatException or Throwable .

However, if we throw a checked exception within the method:

We now have to declare that the method is throwing a Throwable . Why this can be useful is a broad topic that is out of scope for this blog, but there are usages for this specific case.

  • Exception Inheritance

Subclasses that inherit a method can only throw fewer checked exceptions than their superclass:

With this definition, the following method will cause a compiler error:

  • Best and Worst Exception Handling Practices

With all that covered, you should be pretty familiar with how exceptions work and how to use them. Now, let's cover the best and worst practices when it comes to handling exceptions which we hopefully understand fully now.

  • Best Exception Handling Practices
  • Avoid Exceptional Conditions

Sometimes, by using simple checks, we can avoid an exception forming altogether:

Calling this method with a valid index would result in:

But calling this method with an index that's out of bounds would result in:

In any case, even though the index is too high, the offending line of code will not execute and no exception will arise.

  • Use try-with-resources

As already mentioned above, it's always better to use the newer, more concise and cleaner approach when working with resources.

  • Close resources in try-catch-finally

If you're not utilizing the previous advice for any reason, at least make sure to close the resources manually in the finally block.

I won't include a code example for this since both have already been provided, for brevity.

  • Worst Exception Handling Practices
  • Swallowing Exceptions

If your intention is to simply satisfy the compiler, you can easily do so by swallowing the exception :

Swallowing an exception refers to the act of catching an exception and not fixing the issue.

This way, the compiler is satisfied since the exception is caught, but all the relevant useful information that we could extract from the exception for debugging is lost, and we didn't do anything to recover from this exceptional condition.

Another very common practice is to simply print out the stack trace of the exception:

This approach forms an illusion of handling. Yes, while it is better than simply ignoring the exception, by printing out the relevant information, this doesn't handle the exceptional condition any more than ignoring it does.

  • Return in a finally Block

According to the JLS ( Java Language Specification ):

If execution of the try block completes abruptly for any other reason R, then the finally block is executed, and then there is a choice.

So, in the terminology of the documentation, if the finally block completes normally, then the try statement completes abruptly for reason R.

If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).

In essence, by abruptly returning from a finally block, the JVM will drop the exception from the try block and all valuable data from it will be lost:

In this case, even though the try block throws a new IOException , we use return in the finally block, ending it abruptly. This causes the try block to end abruptly due to the return statement, and not the IOException , essentially dropping the exception in the process.

  • Throwing in a finally Block

Very similar to the previous example, using throw in a finally block will drop the exception from the try-catch block:

In this example, the MyException thrown inside the finally block will overshadow the exception thrown by the catch block and all valuable information will be dropped.

  • Simulating a goto statement

Critical thinking and creative ways to find a solution to a problem is a good trait, but some solutions, as creative as they are, are ineffective and redundant.

Java doesn't have a goto statement like some other languages but rather uses labels to jump around the code:

Yet still some people use exceptions to simulate them:

Using exceptions for this purpose is ineffective and slow. Exceptions are designed for exceptional code and should be used for exceptional code.

  • Logging and Throwing

When trying to debug a piece of code and finding out what's happening, don't both log and throw the exception:

Doing this is redundant and will simply result in a bunch of log messages which aren't really needed. The amount of text will reduce the visibility of the logs.

  • Catching Exception or Throwable
Why don't we simply catch Exception or Throwable, if it catches all subclasses?

Unless there's a good, specific reason to catch any of these two, it's generally not advised to do so.

Catching Exception will catch both checked and runtime exceptions. Runtime exceptions represent problems that are a direct result of a programming problem, and as such shouldn't be caught since it can't be reasonably expected to recover from them or handle them.

Catching Throwable will catch everything . This includes all errors, which aren't actually meant to be caught in any way.

In this article, we've covered exceptions and exception handling from the ground up. Afterwards, we've covered the best and worst exception handling practices in Java.

Hopefully you found this blog informative and educational, happy coding!

You might also like...

  • Java: Finding Duplicate Elements in a Stream
  • Spring Boot with Redis: HashOperations CRUD Functionality
  • Spring Cloud: Hystrix
  • Java Regular Expressions - How to Validate Emails

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Entrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs.

Great passion for accessible education and promotion of reason, science, humanism, and progress.

In this article

Make clarity from data - quickly learn data visualization with python.

Learn the landscape of Data Visualization tools in Python - work with Seaborn , Plotly , and Bokeh , and excel in Matplotlib !

From simple plot types to ridge plots, surface plots and spectrograms - understand your data and learn to draw conclusions from it.

© 2013- 2024 Stack Abuse. All rights reserved.

Java Guides

Java Guides

Search this blog, java exception handling interview questions and answers.

Check out complete beginner to expert in-depth exception handling tutorial in Java
  • What is an Exception in Java?
  • How Exception Handling Works in Java
  • What are the Exception Handling Keywords in Java?
  • What is the purpose of the throw and throws keywords?
  • How can you handle an exception?
  • Explain Java Exception Hierarchy?
  • How can you catch multiple exceptions?
  • What is the difference between Checked and Unchecked Exceptions in Java?
  • What is the difference between the throw and throws keywords in Java?
  • What is the difference between an exception and an error?
  • What is OutOfMemoryError in Java?
  • What are Chained Exceptions in Java?
  • How to write custom exceptions in Java?
  • What is the difference between final, finally, and finalize in Java?
  • What happens when an exception is thrown by the main method?
  • What is a try-with-resources statement?
  • What is a stack trace and how does it relate to an exception?
  • What are the Advantages of Java Exceptions?
  • Can you throw any exception inside a lambda expression’s body?
  • What are the rules we need to follow when overriding a method that throws an exception?
  • Java Exception Handling Best Practices

1. What is an Exception in Java?

2. how exception handling works in java.

assignment questions on exception handling in java

3. What are the Exception Handling Keywords in Java?

assignment questions on exception handling in java

4. What is the purpose of the throw and throws keywords?

5. how can you handle an exception, 6. explain java exception hierarchy.

  • Error Class
  • Exception Class

assignment questions on exception handling in java

7. How can you catch multiple exceptions?

8. what is the difference between checked and unchecked exception in java, 9. what is the difference between throw and throws keyword in java, 10. what is the difference between an exception and error.

  • OutOfMemoryError – thrown when the JVM cannot allocate more objects because it is out memory, and the garbage collector was unable to make more available
  • StackOverflowError – occurs when the stack space for a thread has run out, typically because an application recurses too deeply
  • ExceptionInInitializerError – signals that an unexpected exception occurred during the evaluation of a static initializer
  • NoClassDefFoundError – is thrown when the classloader tries to load the definition of a class and couldn’t find it, usually because the required class files were not found in the classpath
  • UnsupportedClassVersionError – occurs when the JVM attempts to read a class file and determines that the version in the file is not supported, normally because the file was generated with a newer version of Java

11. What is OutOfMemoryError in Java?

assignment questions on exception handling in java

12. What is Chained Exceptions in Java?

13. how to write a custom exception in java.

  • Create a new class whose name should end with  Exception  like  ClassNameException . This is a convention to differentiate an exception class from regular ones.
  • Make the class  extends  one of the exceptions which are subtypes of the  java.lang.Exception  class. Generally, a custom exception class always extends directly from the  Exception  class.
  • Create a constructor with a  String  parameter which is the detail message of the exception. In this constructor, simply call the super constructor and pass the message. In Java, there are two types of exceptions – checked and unchecked exception.

14. What is the difference between final, finally and finalize in Java?

15. what happens when an exception is thrown by the main method, 16. what is a try-with-resources statement, 17. what is a stacktrace and how does it relate to an exception, 18. what are the advantages of java exceptions, 19. can you throw any exception inside a lambda expression’s body, 20. what are the rules we need to follow when overriding a method that throws an exception, 21. java exception handling best practices.

  • Clean up Resources in a Finally Block or Use a Try-With-Resource Statement
  • Throw Specific Exception
  • Do not catch the Exception class rather catch specific subclasses
  • Never catch a Throwable class
  • Always correctly wrap the exceptions in custom exceptions so that stack trace is not lost
  • Catch the most specific exception first
  • Don’t ignore exceptions rather log the exceptions
  • Never throw any exception from finally block
  • Don’t use printStackTrace() statement or similar methods
  • Use finally blocks instead of catch blocks if you are not going to handle the exception
  • Validate user input to catch adverse conditions very early in the request processing
  • Throw Exceptions With Descriptive Messages

Related Java Interview Articles

Spring boot interview questions java tricky coding interview questions java string interview questions java string tricky coding questions java main() method interview questions java 8 interview questions top 10 spring mvc interview questions java array interview questions and answers java oops tricky coding questions java programs asked in interview oops interview questions and answers hibernate interview questions jpa interview questions and answers java design patterns interview questions spring core interview questions java exception handling interview, post a comment.

Leave Comment

My Top and Bestseller Udemy Courses

  • Spring 6 and Spring Boot 3 for Beginners (Includes Projects)
  • Building Real-Time REST APIs with Spring Boot
  • Building Microservices with Spring Boot and Spring Cloud
  • Full-Stack Java Development with Spring Boot 3 & React
  • Testing Spring Boot Application with JUnit and Mockito
  • Master Spring Data JPA with Hibernate
  • Spring Boot Thymeleaf Real-Time Web Application - Blog App

Check out all my Udemy courses and updates: Udemy Courses - Ramesh Fadatare

Copyright © 2018 - 2025 Java Guides All rights reversed | Privacy Policy | Contact | About Me | YouTube | GitHub

assignment questions on exception handling in java

Top 50 Java Exception Handling Interview Questions

In the world of software, errors occur all the time. It might be an invalid user input, an external system that is not responding, or a simple programming error. In each of these cases, the errors happen at runtime, and the application has to deal with them. If not, it crashes and is unable to handle additional requests. Java offers a robust mechanism that enables you to handle the exceptional event either in the method where it occurred or one higher in the call stack. Exception handling is the most crucial aspect of Java programming, enabling us to manage runtime errors brought on by exceptions. So let's look at these Java exceptions handling questions and answers that are important for any Java developer preparing for an interview. If you're looking to hire Java developers , too, these questions can be a great reference for tests.

I am looking to hire

I am looking for a job

Java Exception Handling interview questions focus on assessing a candidate's expertise in managing exceptions within Java applications. Java Exception Handling Interview Questions include questions that evaluate the understanding of try-catch blocks, throw-and-throw keywords, custom exception classes, and error handling in API development. Java Exception Handling interview questions ensure a comprehensive evaluation of Java exception handling mechanisms and their application in web service environments.

Java Exception Handling Interview Questions for Freshers

Java Exception Handling Interview Questions for Freshers focus on evaluating a candidate's understanding of the mechanisms in Java for handling errors and exceptions. Java Exception Handling Interview Questions test knowledge of how Java applications manage runtime errors and maintain smooth operations. Freshers are expected to demonstrate familiarity with try-catch blocks, the throws keyword, and the hierarchy of exceptions in Java.

What is an exception in Java and how does it differ from an error?

View Answer

Hide Answer

An exception in Java is an abnormal event that disrupts the normal flow of a program. An exception differs from an error in that exceptions are recoverable during runtime, while errors are typically irrecoverable and indicate serious issues in the system.

Can you explain the try-catch block in Java?

The try-catch block in Java is used to handle exceptions. Code within the try block is monitored for exceptions, and if any occur, they are caught and processed by the catch block. This ensures graceful error handling without program termination.

What is the purpose of the finally block in Java exception handling?

The finally block in Java is used to execute code that should always run, regardless of whether an exception occurred or not. The finally block is commonly used for resource cleanup, ensuring proper closure of files, database connections, etc.

How does the throws keyword function in Java?

The throws keyword in Java is used in method declarations to indicate that the method may throw certain exceptions. The throws keyword signals to the calling code that it needs to handle these exceptions or propagate them further.

What is the difference between checked and unchecked exceptions in Java?

Checked exceptions in Java are checked at compile-time, requiring explicit handling, while unchecked exceptions are runtime exceptions not checked at compile-time. Unchecked exceptions usually result from programming errors and are not forced to be handled.

Can a try block exist without a catch block in Java?

Yes, a try block can exist without a catch block in Java. It can be followed by a finally block, which ensures that code within it runs regardless of whether an exception occurred or not.

How do you handle multiple exceptions in a single catch block in Java?

Multiple exceptions are handled in a single catch block by separating them with the pipe (|) symbol. This allows concise exception handling for different scenarios within a single catch block.

What is a stack trace, and how is it useful in Java exception handling?

A stack trace in Java is a detailed report of the call stack at the point where the exception occurred. A stack trace provides information about the sequence of method calls, aiding developers in identifying the root cause of the exception.

Can a catch block exist without being preceded by a try block in Java?

No, a catch block cannot exist without being preceded by a try block in Java. The try block is essential for monitoring code that may throw exceptions, and the catch block is meant to handle those exceptions.

Your engineers should not be hiring. They should be coding.

Help your team focus on what they were hired for. Flexiple will manage your entire hiring process and scale your tech team.

How can you create a custom exception in Java?

To create a custom exception in Java, you need to extend the Exception class or one of its subclasses. This new class represents your custom exception, and you can add specific details or behavior as needed.

What is the throw keyword, and how is it used in Java?

The throw keyword in Java is used to explicitly throw an exception. The throw keyword is followed by an instance of the Exception class or its subclasses. This allows developers to handle exceptional scenarios by triggering specific exceptions.

In Java, what is the difference between final, finally, and finalize?

The 'final' is a keyword used to declare constants or prevent method overriding in Java. 'finally' is a block used in exception handling for cleanup, and 'finalize' is a method called by the garbage collector before an object is reclaimed.

How does exception handling ensure robustness in a Java application?

Exception handling in Java ensures robustness by providing a structured way to handle unexpected situations. Exception handling prevents abrupt termination, allows for graceful recovery, and maintains the integrity of the application during runtime errors.

Can you manually throw an exception in Java? If so, how?

Yes, an exception can be manually thrown in Java using the 'throw' keyword followed by an instance of the Exception class or its subclasses. This allows developers to create custom error scenarios and handle them appropriately.

What happens if an exception is not caught in Java?

If an exception is not caught in Java, it leads to abnormal termination of the program. The default behavior is to print the exception details and the stack trace, helping developers identify and fix the issue.

Is it possible to catch more than one type of exception in a single catch block in Java? If yes, how?

Yes, it is possible to catch more than one type of exception in a single catch block in Java by separating the exception types with the pipe (|) symbol. This allows concise and effective handling of multiple exception scenarios.

What is the role of the try-with-resources statement in Java?

The try-with-resources statement in Java is used to automatically close resources like files or database connections when they are no longer needed. The try-with-resources statement simplifies resource management and reduces the likelihood of resource leaks.

How do you handle an exception thrown by a method in Java?

To handle an exception thrown by a method in Java, you can use a try-catch block around the method call. This allows you to catch and handle the exception, ensuring smooth program flow even in the presence of errors.

Can you override a method that throws an exception in Java?

Yes, a method that throws an exception in Java can be overridden in a subclass. However, the overriding method can only throw the same exception type or its subtype. This ensures compatibility with the overridden method's exception declaration.

What are the common runtime exceptions in Java?

Common runtime exceptions in Java include NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException. These exceptions occur during the execution of a program and typically indicate logical errors or unexpected conditions.

How can exception handling lead to better error management in Java applications?

Exception handling in Java leads to better error management by allowing developers to identify, handle, and recover from unexpected situations. This improves the overall reliability and user experience of Java applications.

What is the difference between the Error and Exception classes in Java?

In Java, 'Error' is a class representing serious errors that are generally not recoverable, while 'Exception' is a class for exceptional conditions that can be caught and handled. Errors usually indicate severe issues like out-of-memory situations.

In what scenarios is it appropriate to use a finally block in Java?

A finally block in Java is appropriate in scenarios where resource cleanup or finalization is required, regardless of whether an exception occurred or not. A finally block ensures that critical code is executed, promoting good coding practices.

How does the catch or declare rule apply in Java exception handling?

The catch or declare rule in Java exception handling requires methods that can throw checked exceptions to either catch those exceptions or declare them in their method signature using the 'throws' keyword.

What is the significance of the Exception class hierarchy in Java?

The Exception class hierarchy in Java provides a structured way to represent and handle different types of exceptions. The Exception class hierarchy allows developers to categorize exceptions based on their characteristics and handle them appropriately.

Java Exception Handling Interview Questions for Experienced

Java Exception Handling Interview Questions for Experienced is a comprehensive guide that challenges seasoned Java developers with advanced questions on handling exceptions. Java Exception Handling Interview Questions test the developer's deep understanding of Java's exception handling mechanisms, such as try-catch blocks, throw and throws keywords, and custom exception creation. Java Exception Handling Interview Questions for Experienced delves into scenarios involving stack traces, exception propagation, and best practices in managing runtime and checked exceptions.

How does exception chaining work in Java?

Exception chaining in Java involves capturing one exception and throwing another while preserving the original exception's information. This facilitates better debugging and provides a comprehensive view of the error context.

Can you explain the difference between throw and throws in the context of Java exception handling?

The difference between throw and throws in the context of Java exception handling is that the 'throw' is used to manually throw an exception, while 'throws' is used in method declarations to specify the exceptions that the method may throw. 'throw' is singular, indicating a specific exception, while 'throws' is plural, listing potential exceptions.

How is exception handling in Java different from other programming languages like Python or C++?

Exception handling in Java differs from other languages like Python or C++ in syntax and approach. Java uses try-catch blocks for exception handling, while Python uses try-except, and C++ uses try-catch with different syntax and semantics.

In what scenarios would you use a nested try block in Java?

Nested try blocks in Java are used when different sections of code within a method may throw exceptions. The outer try-catch block handles broader exceptions, while nested try-catch blocks address specific exceptions within the inner code sections.

How does the JVM handle an exception thrown by the main method?

When an exception is thrown by the main method in Java, the JVM searches for an appropriate exception handler. If not found, the default exception handler terminates the program, displaying the exception details and stack trace.

Can you discuss the performance implications of using exceptions in Java?

Using exceptions in Java for normal control flow can impact performance negatively. Exceptions should be reserved for exceptional conditions, as their overhead is higher than standard program control mechanisms like conditionals.

How would you handle a checked exception in a lambda expression in Java?

To handle a checked exception in a lambda expression in Java, you can either wrap the lambda body with a try-catch block or use the 'throws' clause in the functional interface's method signature.

Can you explain how to use custom exceptions for business logic validation in Java?

Custom exceptions in Java can be used for business logic validation by creating specific exception classes representing validation failures. Throwing these custom exceptions allows for clear and targeted error handling in business logic.

What is the purpose of the InterruptedException in Java, and how should it be handled?

InterruptedException in Java is thrown when a thread is interrupted during its sleep or wait state. InterruptedException is handled by either rethrowing it or handling it gracefully, considering the thread's interrupted status and taking appropriate action.

How do you handle exceptions in a multi-threaded environment in Java?

In a multi-threaded environment in Java, exceptions can be handled by encapsulating thread-specific code within try-catch blocks. Proper synchronization mechanisms and error-handling strategies are employed to ensure thread safety.

Can you differentiate between ExceptionInInitializerError and NoClassDefFoundError in Java?

ExceptionInInitializerError in Java occurs when an exception is thrown during class initialization, while NoClassDefFoundError happens when the JVM cannot find the class definition during runtime. ExceptionInInitializerError in Java represent different phases of class loading and initialization.

How do you log exceptions in Java effectively?

Exceptions in Java can be effectively logged using logging frameworks like Log4j or java.util.logging. Logging helps in recording detailed information about exceptions, aiding developers in identifying and resolving issues.

Is it a good practice to use exceptions for control flow in Java? Why or why not?

Using exceptions for control flow in Java is generally not a good practice. Exceptions are designed for exceptional conditions, and using them for routine program control can lead to performance issues and make the code less readable.

What are the best practices for handling null pointer exceptions in Java?

Best practices for handling null pointer exceptions in Java include validating objects before dereferencing, using the Optional class, and providing meaningful error messages. Defensive coding practices can help prevent null pointer exceptions.

How can you avoid memory leaks in Java exception handling?

Memory leaks in Java exception handling can be avoided by releasing resources in the finally block, using try-with-resources for automatic resource management, and ensuring proper handling of custom objects to prevent unnecessary memory retention.

Can you explain the concept of exception propagation in Java?

Exception propagation in Java involves the transmission of an exception from the point it occurred to its eventual handling. Exception propagation traverses through the method call stack until a suitable catch block is found or until the program terminates.

How do you handle exceptions in a Java servlet?

Exceptions in a Java servlet can be handled using the servlet's error-handling mechanisms, such as the error-page element in the web.xml file. Custom exception handling logic is implemented within the servlet code.

What is the significance of the RuntimeException class in Java?

The RuntimeException class in Java is a subclass of Exception and represents unchecked exceptions. The RuntimeException is often used for runtime exceptions that indicate programming errors, and handling it is not enforced by the compiler.

How do you test exception handling in Java applications?

Exception handling in Java applications can be tested by deliberately inducing exceptions in the code, using unit testing frameworks like JUnit. This ensures that the application handles exceptions as expected and gracefully recovers when necessary.

What are the common pitfalls in Java exception handling, and how can they be avoided?

Common pitfalls in Java exception handling include catching generic exceptions, ignoring exceptions, and excessive use of checked exceptions. Common pitfalls can be avoided by using specific exception types, proper logging, and handling exceptions at appropriate levels.

Can you explain how to handle checked exceptions in stream operations in Java 8 and above?

Checked exceptions in stream operations in Java 8 and above can be handled by wrapping the code in a try-catch block or using the 'throwing' variant of functional interfaces. The exception is rethrown as an unchecked exception.

What role does the Throwable class play in Java exception handling?

The Throwable class in Java is the root class for all exceptions and errors. The Throwable class provides common methods like getMessage() and printStackTrace(), allowing developers to access and handle exception information consistently.

How would you refactor legacy Java code to improve exception handling?

To improve exception handling in legacy Java code, one can refactor by replacing generic exception handling with specific exception types, introducing try-with-resources for resource management, and implementing consistent error-handling strategies.

Can you explain the process of creating custom exception hierarchies in Java?

Creating custom exception hierarchies in Java involves extending the Exception class or its subclasses to represent specific types of exceptions. By organizing exceptions into a hierarchy, developers can handle them more effectively based on their characteristics.

How do assertions and exceptions complement each other in Java programming?

Assertions and exceptions in Java complement each other by serving different purposes. Assertions are used for debugging and testing, indicating assumptions in the code, while exceptions handle unexpected runtime errors during regular program execution.

Tips to Answer Java Exception Handling Interview Questions

Demonstrate a clear understanding of exceptions, their types, and handling mechanisms when answering Java Exception Handling interview questions. Java Exception Handling involves try, catch, and finally blocks, and understanding their use is crucial. Ensure clarity in explaining the difference between checked and unchecked exceptions in Java. Java Exception Handling requires distinguishing between error and exception, and this distinction is fundamental to Java programming. Explain the importance of the try-catch block in Java Exception Handling, as this structure is essential for catching and handling exceptions. In Java Exception Handling, the finally block always executes, regardless of whether an exception occurs

Ideal structure for a 60‑min interview with a software engineer

assignment questions on exception handling in java

Get 15 handpicked jobs in your inbox each Wednesday

Build your dream team

1-stop solution to hire developers for full-time or contract roles.

Find your dream job

Handpicked opportunities with top companies for full-time and contract jobs.

Interview Resources

Want to upskill further through more interview questions and resources? Check out our collection of resources curated just for you.

Browse Flexiple's talent pool

Explore our network of top tech talent. Find the perfect match for your dream team.

  • Programmers
  • React Native
  • Ruby on Rails

HackerTrail Logo

Java Exception Handling Interview Questions and Answers 2023

assignment questions on exception handling in java

Any Java interview is incomplete without Java exception handling interview questions.  Your Java programs can cope up with the unforeseen circumstances, called exceptions, quite efficiently through Java Exception handling which is a robust and user-friendly mechanism to handle errors in a Java program.

In this article, we will be covering the 20 most frequently asked exception handling in Java interview questions and answers for experienced and beginners to help them ace the interview. 

The topics we will be covering are: 

Introduction to Exception handling in Java

  • What is Java Exception Handling?
  • Why do you need Java Exception Handling?
  • What is the mechanism for handling exceptions in Java?

The Java Exception Hierarchy

  • What is the Java Exception Hierarchy?
  • What is the difference between Errors and Exceptions?

Exception Handling Interview Questions: Types of Exceptions in Java

  • What are the types of Exceptions in Java?
  • How do you implement user-defined exception handling in Java?
  • What are the dissimilarities between the two types of Java exceptions?

Exception Handling Interview Questions: Types of Exception Handling Keywords

  • What are the different keywords in Exception handling in Java?
  • What is the difference between throws and throw keywords in Java?
  • How to differentiate between the finally, final, and finalize keywords?

Exception Handling Interview Questions: Catching Exceptions in Java

  • What is try-with-resources statement in Java?
  • What is stack trace in Java and why is it important in exception handling?
  • What is a nested try-catch block?
  • What is a multi-catch block in Java?
  • What are chained exceptions in Java?
  • How do you catch Multiple Exceptions in a single block of code?
  • What will be the result of the main method throwing an exception?

Exception Handling Best Practices

  • What are the best practices in Java exception handling?
  • How to use exception handling with method overriding?

Introduction to Exception handling in Java

1. what is java exception handling.

An exception in Java  is an occurrence of an unusual event at runtime, which interrupts the normal functioning of the program. If the program is not guided what to do in the case of an exception, it will terminate abnormally at the point of exception, without further executing the program. To avoid such program failures, there is a mechanism called Exception Handling in Java that prevents programs from failing under unanticipated situations. A few examples of exceptions occurring at run-time are:

  • A program trying to access a non-existent file 
  • Invalid data entered by a user  
  • A program executing an invalid SQL query.  

Explore the Job Openings in APAC

2. Why do you need Java Exception Handling?

If an exception occurs and there is no try and catch block to monitor and handle it, the program will terminate without executing the subsequent lines. Exception handling in Java is therefore required to ensure that the application does not end abruptly, execute catch and finally blocks in it, and tells it what to do in case of an exception.   

3. What is the mechanism for handling exceptions in Java?

Exception handling in Java is achieved through try, catch, and finally blocks.

  • try block : The lines of code that are probable of causing an error are enclosed inside a try block so that they can be monitored for exceptions. The try block must be followed by either catch block or finally block or both, otherwise the program will throw a compilation error.
  • catch block : If a try block throws an exception, the control directly goes to the catch block defined for that particular exception.  If no exception occurs, the program skips the catch block and executes normally.
  • finally block : This block is optional, but if present, it always gets executed irrespective of the occurrence of an exception in the try block. The finally block can only be used in conjunction with the try-catch block. 

Test your coding skills here

4. What is the Java Exception Hierarchy?

exception handling in java class hierarchy diagram

When an exception occurs during the execution of an application, the JVM creates an Exception object in memory and interrupts the normal flow of the program. The throwable class creates a stack trace and also contains the relevant error message which can be obtained through getMessage() method. JVM then finds and executes a piece of code known as Exception Handler which processes the object of Exception Class.

5. What is the difference between Errors and Exceptions?

The key differences between errors and exceptions in Java are:

6. What are the types of Exceptions in Java?

There are two types of exceptions based on how they are handled by JVM: 

Checked Exceptions

Checked Exceptions are known during the compilation process. The compiler checks whether the exception is handled or not and throws an error in case it is not handled programmatically. Examples of such exceptions are  SQLException, IOException, InvocationTargetException, and ClassNotFoundException.  

Unchecked Exceptions

Unchecked Exceptions or run-time exceptions occur during program execution. These exceptions are not caught during the compilation process. All the exceptions under  Error  and  RuntimeException  classes are unchecked. Few examples of unchecked exceptions are ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.

Based on how the exceptions are defined, here are other exception types  

Built-In Exceptions

The exceptions that already exist in the Java libraries are known as Built-in exceptions. All the checked and unchecked exceptions fall under this category.

User-defined Exceptions

If a user comes across an exception scenario that is not covered by the built-in libraries, Java provides a provision to create a custom exception. A custom or user-defined exception can be constructed by creating a subclass of the ‘Exception’ class.

7. How do you implement user-defined exception handling in Java?

Here are the steps to execute  user-defined exception handling in Java

  • Create your user-defined exception class by inheriting the built-in Exception class.
  • Next, create a constructor for your custom exception class. You can do this by either writing a default constructor within the CustomException or, you may create a parameterized constructor with a string argument.[Text Wrapping Break] This parameterized constructor can be used to store the details of the exception.
  • The ‘throw’ keyword is used to raise the user-defined exception. We create an object of the user-defined exception class and the throw clause to initiate that object.

Below is a user-defined  exception handling program in Java : 

8. What are the dissimilarities between the two types of Java exceptions?

Here are the differences between the exception types in Java 

9. What are the different keywords in Exception handling in Java?

Five keywords manage Java exception handling. These are: try, catch, throw, throws, and finally. We have already seen try, catch, and finally. Let us differentiate and understand the throw and throws keyword.

10. What is the difference between throws and throw keywords in Java?

The throws keyword is used to declare an exception in the signature of a method. This keyword can throw multiple exceptions, checked and unchecked both, separated by commas.

The method declaration will look like this:

public static void throwsKeywordExample() throws SocketException, ConnectionException

The throw keyword on the other hand is used to throw exceptions explicitly inside a method.  Unlike throws, there is only one exception per the ‘throw’ keyword.  

11. How to differentiate between the finally, final, and finalize keywords?

final, finally and finalize are three different keywords in Java all with specific usage. But they are often confused due to similarity names. Let us understand each of them:

Final: Final is a keyword that is used to apply limitations on a class, function, or variable. You cannot inherit a final class, you can’t override a final method and you can’t change the value of a variable declared as final. 

Finally: finally keyword is used along with the try-catch block. This block consists of statements that need to be executed regardless of whether an exception occurs or not, for example, the closing of a database connection, etc.

Finalize: The finalize() method of the Object class is used for clean up processing right before the object is garbage collected. The garbage collector calls this method when it finds that there are no more references to a particular object. 

Exception Handling Interview Questions: Catching Exceptions in Java 

12. what is try-with-resources statement in java.

A try statement that declares one or more resources is called a try-with-resources statement. Examples of resources are input and output stream, a database connection, etc. All such resources need to be closed at the end of the program execution. This statement ensures that the code closes the resources that were opened by the try keyword.

Here is an example taken from the oracle Java docs. 

The below example reads the first line of a file via an instance of BufferedReader.  BufferedReader is the resource here that needs to be closed after its usage in the program.  

The try-with-resources is declared by declaring the resource object in parentheses immediately after the try keyword. As a BufferedReader instance is declared inside the try-with-resource statement, it will be closed even if the try statement terminates abruptly. 

13. What is stack trace in Java and why is it important in exception handling?

A stack trace is a list of frames that contains information about methods that were called during your application’s execution. A stack trace gives the names of the methods and classes that were called throughout the lifecycle of the application until the occurrence of an exception.

In Java exception handling, stack trace can be used as a powerful debugging tool as it helps in determining the exact point where the exception occurred in the application and the reason why it occurred. 

14. What is a nested try-catch block?

In exception handling, a nested try-catch block is one where we use a try-catch block inside another.

Here is an example of nested try-catch block:  

The above program will try to execute the inner try statement first. If the inner try statement doesn’t find a matching catch statement, the control will be transferred to the subsequent try block. The program will keep looking for catch statements until it succeeds or until all the nested try statements are executed. If no matching catch statement is found, the JRE will handle the exception. 

15. What is a multi-catch block in Java?

There could be a scenario where a single piece of code can cause multiple exceptions. You can handle this situation by creating several catch clauses, each catching a different exception. When the program throws an exception, it inspects the catch statements in the order in which they appear. The first catch whose type matches the type of exception is executed. Below is an exception handling program in Java to understand the multi-catch block. 

16. What are chained exceptions in Java?

By using chained exceptions, you can associate one exception with another exception, i.e, the second exception is generally the cause for the first exception.

For instance, consider a method that throws an ArithmeticException because it attempted to divide by zero. However, the real cause for that exception was an I/O error that improperly set the divisor. Though the method ought to throw an ArithmeticException, as it is the error that occurred, the calling code should also know that the actual cause was an I/O error.

17. How do you catch Multiple Exceptions in a single block of code?

There are three ways by which you can catch multiple exceptions in a single code block:

  • By using a catch block that handles all the exception types being thrown by a method:

A thing to remember is that the above code is not a recommended method though. It uses the generic Exception class as it handles all the exceptions. However, it is best to use exception handlers that are precise to the exceptions being thrown.

  • The second way is to implement multiple catch blocks: 

We need to keep in mind that if the exceptions share an inheritance relationship, the child type has to come before the parent type otherwise it will result in a compilation error. 

  • The third is to use a multi-catch block which we have already covered in the previous section. 

18. What will be the result of the main method throwing an exception?

If an exception is thrown by the main() method, the Java Runtime Environment will terminate the application and print the stack trace in-system console along with the exception message.

19. What are the best practices in Java exception handling?

Below are the top 10 best practices to follow for implementing exception handling in Java

  • You ought to use a finally block to clean-up resources. Alternatively, you can use a try-with-resources statement.
  • You should throw specific exceptions as far as possible.
  • You must not catch the Exception class, instead you should catch specific subclasses.
  • The Throwable class is not to be caught.
  • Make it a habit to correctly wrap the built-in exceptions in custom exceptions to ensure a readable stack trace.
  • Catch the most specific exception first
  • No exception should be thrown from the finally block
  • Avoid calling printStackTrace() or similar methods within your code.
  • Your code should validate the user input to minimize user errors as well as catch an adverse condition fairly early.
  • Include descriptive messages while throwing exceptions.

20. How to use exception handling with method overriding?

  • When exception handling is used with method overriding, it causes ambiguity. The compiler gets confused as to which method definition it should follow, the one in the superclass or the subclass. Certain rules can help prevent this ambiguity while using exceptions with inheritance.
  • If the parent class method does not throw exceptions, the overriding class method should throw only unchecked exceptions. A checked exception will result in a compilation error.
  • In the case of the parent class method throws checked exceptions, the child class method may throw any unchecked exception as well as any or all of the checked exceptions thrown by the superclass.
  • The child class can also declare a few checked exceptions that the parent class does not throw, but it needs to ensure that the scope of such checked exceptions in the child class is narrower as compared to the parent class.
  • When the superclass throws an unchecked exception, the subclass method can throw either none or any number of unrelated unchecked exceptions.

You can understand  exception handling in method overriding  through code better.

Now when you are done with the most popular Java exception handling interview questions, we at Hackertrail are here to connect you to the right opportunities in your domain. 

Other Backend Technology Interview Questions and Answers

C Programming Language Interview Questions | PHP Interview Questions | .NET Core Interview Questions | NumPy Interview Questions | API Interview Questions | FastAPI Python Web Framework | OOPs Interview Questions and Answers | Java Collections Interview Questions | System Design Interview Questions | Data Structure Concepts | Node.js Interview Questions | Django Interview Questions | React Interview Questions | Microservices Interview Questions | Key Backend Development Skills | Data Science Interview Questions | Python Interview Questions | Java Spring Framework Interview Questions | Spring Boot Interview Questions .

Related Articles

Must Know Questions and Answers for Google Ads Interview

50+ Must-Know Google Ads Interview Questions and Answers

TweetLinkedInShare The Google Ads is an online advertising platform offered by Google. Google allows businesses and advertisers to create and display ads across Google’s vast…

Social Media Marketing Top 50 Interview Questions and Answers

Social Media Marketing Most Updated Interview Questions and Answers

TweetLinkedInShare Generic Social Media Questions and Answers   1. What is Social Media Marketing? Social Media Marketing (SMM) strategy involves using social media platforms to…

C Programming Language Interview Questions and Answers

C Programming Language Interview Questions and Answers 2023

TweetLinkedInShare To make any programming language interview successful, you must strengthen your foundational programming knowledge. C language is that foundation, and you must enhance this…

There was a problem reporting this post.

Block Member?

Please confirm you want to block this member.

You will no longer be able to:

  • See blocked member's posts
  • Mention this member in posts
  • Invite this member to groups
  • Message this member
  • Add this member as a connection

Please note: This action will also remove this member from your connections and send a report to the site admin. Please allow a few minutes for this process to complete.

assignment questions on exception handling in java

  • Guest Posts

Exception Handling in Java (with Real Examples)

Java has been one of the most widely used programming languages among developers worldwide for years. So naturally, it is a popular choice for those beginning their careers in development.

Learning Java requires more than just knowing the proper syntax and effective code hygiene. Any developer who hopes to use Java for commercial development must be able to quickly and competently identify and recognize errors in their code.

While the features of code editors go a long way toward pointing out basic programming errors, other issues are more easily identified during program compilation or in runtime environments. And one of the primary tools developers have for addressing anomalous conditions at runtime is exception handling.

Both novice and more experienced programmers should understand how to use exception handling to improve their code. This article discusses the basics of exception handling in Java and how Sentry can help make exception handling simple and more powerful.

What is an exception?

Formally, an exception in Java is “an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.” There are many typical causes for exceptions in Java, including:

  • Loss of network connectivity
  • Invalid input data
  • Requests for missing or non-existent files
  • Exceeding memory limits for the Java Virtual Machine (JVM)
  • Code errors

Officially, exceptions are distinct from errors because errors are more serious issues that the application “should not try to catch.” Most developers, however, consider errors to be just a subset of exceptions.

What happens when a program method throws an exception?

Errors encountered during runtime create exception objects containing basic information about the exception, including the type of exception generated and the system’s state at the time of the exception. The method then throws the exception to the runtime system for processing.

After receiving an exception, the runtime system tries to find a way to resolve it. Tracing backward through the call stack from the method where the exception occurred, the runtime system looks for an existing method that can process the exception. These methods are called exception handlers. If no method in the call stack can handle the exception, both the runtime system and the application stop.

Why is exception handling important?

Exception handling is crucial for the proper functioning of your applications. With exception handling, developers define the steps for addressing compilation or runtime errors to ensure that there are no interruptions of program flow. As a result, applications are more stable and have a better user experience. And because coding errors that lead to exceptions can be points of vulnerability for cyberattacks, effective exception handling can lead to more secure code.

What types of exceptions exist in Java?

To best understand how to use exceptions and exception handling, you must be familiar with the types of exceptions built into Java.

Java’s built-in exceptions fall into two broad categories: checked and unchecked exceptions. Checked exceptions are compile-time rather than runtime exceptions. During compilation, the compiler specifically looks for checked exceptions and whether the program includes exception handlers. If no appropriate exception handler exists for a checked exception, the compiler generates a compilation error.

In contrast, unchecked exceptions are runtime exceptions, and the compiler will generally ignore them.

More advanced Java programmers can also create custom exceptions to gain even deeper insight into the functioning of their code. Custom exceptions can be tremendously useful for pinpointing issues with specific business logic that the built-in Java exceptions would not catch, helping your business build the best possible reputation for its products.

What is the hierarchy of exception classes?

Java establishes a hierarchy for exceptions under the Throwable class. The first level of the class divides issues into exceptions and errors. The exceptions hierarchy is broadly divided by exception type. Specifically, the broadest subclasses of exceptions are:

  • IOException
  • ReflectiveOperationException
  • CloneNotSupportedException
  • InterruptedException
  • RuntimeException

All RuntimeExceptions are unchecked exceptions, while all remaining exceptions are checked.

Common examples of handling exceptions in Java

While the complete list of built-in exceptions is extensive, a few are more frequently encountered than others.

Common checked exceptions

Many checked exceptions arise when the program cannot find items it expects to exist. These exceptions use phrases like NotFound or NoSuch in their name and are part of the ReflectiveOperationException subclass.

ClassNotFoundException

This is one of the most common exceptions in Java. There are several situations where a ClassNotFound exception can occur, including:

Java Classloader or Class.forName() methods cannot find a specified class in the classpath when attempting to load the class.

Attempting to load Java database connectivity (JDBC) files using Class.forName() if the jar file is not in the class’s path.

It is simple to set up a test of the ClassNotFound exception using a try-catch block . The try-catch block is specifically intended to identify potential exceptions. The try statement encloses potentially problematic code, and the catch defines the exception for which you are testing and performs any actions the developer wants to occur in the event of an exception. Importantly, rather than terminating when the exception occurs, the program continues to run.

When this code runs, the compiler outputs a ClassNotFound exception:

Another example of this type of reflection exception is the FileNotFoundException , which can occur when a file is absent, or the application does not have sufficient permission to access it.

Resolving the ClassNotFound exception involves reviewing your classpath to ensure that all necessary classes and jar files are appropriately identified.

NoSuchMethodException

Not surprisingly, Java throws a NoSuchMethod exception when attempting to call a non-existent class method or a private method. A simple example shows how this exception can arise when a developer is not careful about defining and using method names.

Note that we did not use a try-catch block in this example. Unlike ClassNotFoundException, NoSuchMethodException can not be thrown in a try-catch block.

During compilation, you will get a missing method error, although it will show differently than with ClassNotFoundException:

Interrupted Exception

Java throws an InterruptedException if a thread that is either occupied or not currently active (e.g., sleeping or waiting) is interrupted. You can create an interruption to show how this exception works:

After creating the InterruptedThread class, starting a thread, making it sleep for 100 ms, and then introducing an interrupt, Java throws an InterruptedException:

InvocationTargetException

This exception is actually an indicator of an underlying exception in a method. Java throws the exception when an attempt is made to invoke a method that throws the primary exception. InvocationTargetException does not provide specifics on the underlying exception, although developers can use the getCause() method for further information.

Common unchecked exceptions

Recall that unchecked examples only arise at runtime rather than appearing during compilation.

IllegalArgumentException

An illegal argument exception is thrown when input to a method is of the wrong type; for example, an array is passed when the method accepts only integer input or if the input is out of a specified input range. You can use the throw exception statement or try-catch blocks to create error messages if a user submits improper input data.

Similar exceptions exist for various other conditions, such as ArrayIndexOutofBoundException or NumberFormatException.

ArithmeticException

As its name implies, Java throws this exception if the program attempts an arithmetic operation that is inconsistent with Java operations. The most common example is dividing by zero.

As you can see, the program not only prints out the stack trace to show the exception but also outputs an error message for the user:

These are just a few of the built-in exceptions that developers can use to control application flow, inform users and themselves when there are issues in the code, and build more robust and stable applications. For more on exceptions, see the Java online documentation.

How Sentry can help monitor and resolve exceptions

Your compiler and runtime environments provide basic information on exceptions, but it can be unhelpful. Products like Sentry provide greater visibility into your code and exceptions, making it simple for you to quickly and easily see all unhandled exceptions in a way that allows you to prioritize your correction efforts easily.

Sentry has several features that make it easier for you to understand what your exceptions are, how they are related, and how they tie to other components like APIs. It organizes similar exceptions into issues, minimizing the time needed to review and triage exceptions, and has built-in algorithms for grouping issues which developers can also define using their own grouping criteria.

With its distributed tracing methods , Sentry also monitors performance and highlights each issue’s impact on users, including how exceptions impact application latency. And using TraceView , Sentry provides more extensive information about each exception.

While knowing what features are available is useful, seeing Sentry in operation brings its issue handling benefits to life. For a particular issue, Sentry shows you how frequently it is occurring and how many users it impacts, making it easier for you to quickly prioritize your remediation efforts.

You can then hover over an issue to get more specifics about what parts of the code give rise to the exceptions.

And for even greater detail, you can follow the dropdown next to each specific code item to see the code itself.

In addition, with the breadcrumbs feature, developers can visualize a detailed timeline of the events that occurred before a specific error.

As with other Sentry features, you can customize breadcrumbs to meet your own needs and debugging tactics.

Sentry knows that you may have sensitive data that you must protect at all times (e.g., user credentials). They apply advanced data scrubbing algorithms to redact sensitive information from your data sources. You can also define and implement your own data scrubbing methods.

Sentry also monitors performance and highlights each issue’s impact on users, including how exceptions impact application latency. Sentry’s Performance Monitoring features give you insight into the success or failure of transactions and how they are impacting your users.

You can drill down through transactions to see the users involved and the individual transaction traces for each individual. And for each trace, you can drill down even further to give you even greater visibility.

Even the most advanced tool will fail if it isn’t simple to use and understand. So Sentry provides a rich set of easily comprehensible, customizable overview dashboards so you can immediately assess the health of your application. With easily added dashboard widgets, you can build a view that focuses on your primary issues of interest.

It is obvious how Sentry simplifies the developer’s task of tracing and resolving issues and exceptions.

These are only a few of the many features that make Sentry a must-have addition to the development toolbox for Java developers serious about exception handling. For more detailed information, check out their documentation or signup to get started.

More from the Sentry blog

A peek at your privacy.

Here’s a quick look at how Sentry handles your personal information (PII).

Who we collect PII from

We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.

What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.

PII we may collect about you

  • PII provided by you and related to your
  • Account, profile, and login
  • Requests and inquiries
  • PII collected from your device and usage
  • PII collected from third parties (e.g., social media)

How we use your PII

  • To operate our site and service
  • To protect and improve our site and service
  • To provide customer care and support
  • To communicate with you
  • For other purposes (that we inform you of at collection)

Third parties who receive your PII

We may disclose your PII to the following type of recipients:

  • Subsidiaries and other affiliates
  • Service providers
  • Partners (go-to-market, analytics)
  • Third-party platforms (when you connect them to our service)
  • Governmental authorities (where necessary)
  • An actual or potential buyer

We use cookies (but not for advertising)

  • We do not use advertising or targeting cookies
  • We use necessary cookies to run and improve our site and service
  • You can disable cookies but this can impact your use or access to certain parts of our site and service

Know your rights

You may have the following rights related to your PII:

  • Access, correct, and update
  • Object to or restrict processing
  • Opt-out of marketing
  • Be forgotten by Sentry
  • Withdraw your consent
  • Complain about us

If you have any questions or concerns about your privacy at Sentry, please email us at [email protected]

If you are a California resident, see our Supplemental notice .

assignment questions on exception handling in java

RuntimeException sub classes : Error sub classes : ArithmeticException ClassCirculatoryError ArrayIndexOutofBoundException ClassFormatError ArrayStoreException Error ClassCasteException IllegalAccessError IlegalArgumentException IncompatibleClassChangeError IndexOutofBoundException InstantiationError NegativeArraySizeException LinkageError NullPointerException NoCassDefFoundError NumberFormatException NoSuchFieldError SecurityException NoSuchMethodError StringIndexOutofBoundException OutofMemoryError StackOverflowError Exception sub classes: Throwable ClassNotFoundException UnknownError DataFormatException UnsatisfiedLinkError IllegalAccessException VerifyError InstantiationException VirtualMachineError InterruptedException NoSuchMethodException RuntimeException
try { // block of code } catch ( ExceptionType1 e) { // Exception handling routine for ExceptionType1 (optional) } catch (ExceptionType2 e ) { // Exception handling routine for ExceptionType2 (optional) } . . . catch (ExceptionType_n e) { // Exception handling routine for ExceptionType_n (optional) } finally { // Program code of exit (optional) }
C:\> java DivideZero // To run the Application DivideZero
One can notice the output then : Java . lang . Arithmetic Exception : / by zero at DivideZero.Any Function (DivideZero.Java : 3) at DivideZero.main (DivideZero.Java : 7)
int wrongMath ( ) { int n = 100; int result ; for (int i = 9; i > -1; i- - ) result = n % i; // modulo remainder. return (result ); }
void wrongArrayAccess ( ) { int anArray = new int[10] ; // An array of size having index 0,1,..,9 ��.. anArray[10] = 999 ; // index out of range }
void badArrayStore ( ) { int storeArray = new int[15]; // An array of integers boolean boolArray =new boolean[5]; // An array of booleans System.arraycopy(storeArray, 2, boolArrary, 2, 4); // Copy the element boolArray[3,4,5] into storeArray starting at storeArray[2] }
class ClassA { // a token of a simple class ��� } class ClassB extends ClassA{ // A sub class of ClassA ���. void bMethod ( ) { . . . . } } class Test { void wrongCast ( ) { ClassA anInstanceA = new ClassA( ); ClassB anInstanceB = (Class B ) anInstanceA; // Exception anInstanceB.bMethod ( ); } }
static void wrongArgumentPass (int agru ) { if (argu == 0) throw new IllegalArgumentException ( "Argument cannot be 0 "); int x = 555 / argu; }
Void negativeSizeArray ( ) { int theSize = -5; int foolArray = new int[theSize]; }
void nullPointer ( ) { String myString = null; // myString is a null reference object if ( myString.equals (" Sahara" )) { System.out.println (" Howz!"); } }
void wrongStringIndex ( ) { String theString = " N E R I S T", char theChar = theString.charat(20); // Index should be between 0 and 10 }
Practice 5.1 public class DivideZero { static int anyFunction (int x, int y ){ try { int a = x/y; return a; } catch (ArithmeticException e) { System.out.println ( "Division by zero" ); } return 0; } public static void main (String args[]) { int a,b, result; a=0; b=0; System.out.print("Enter any two integers : "); try{ a = System.in.read(); b = System.in.read(); }catch(Exception e){} result = anyFunction (a, b); System.out.println ( "Result : " + result); } } Find out the types of exceptions.
Practice 5.2 class CommandLineInput { public static void main (String args[ ] { int number, InvalidCount = 0; validCount = 0; for (int i = 0; i Find out the types of exceptions.
Practice 5.3 public class MultiCatch { public static void main (String args[ ]) { try { int i = args.length; // No of arguments in the command line String myString[] = new String[i]; // If i = 0 then myString null pointer error // #1 // if(myString[0].equals(�Java�)); System.out.println("First word is Java !"); System.out.println( " Number of arguments = " + i ); // # 2 // int x = 18/ i; int y[ ] = {555, 999}; // y is an array of size 2 and index are 0,1 // #3 // y[ i ] = x; // Index is out-of-range may occur if i > 1 } catch (ArithmeticException e ) { // To catch the error at #2 System.out.println ( " Div by 0 : "+ e ); } catch (NullPointerException e ) { // To catch the error at #1 System.out.println ( "A null pointer exception :" + e ); } catch (ArrayIndexOutOfBoundsException e ) { // To catch the error at #3 System.out.println ("Array Index OoB : " + e); } } } Find out the types of exceptions.
Practice 5.4 import java.lang.*; public class exceptions{ public static void main(String Args[]) throws Exception{ int[] array = new int[3]; try{ for (int i=0;i Find out the types of exceptions.
Practice 5.5 class ExceptionTest { public static int j; public static void main (String args[ ] ) { for (int i = 0; i Find out the types of exceptions.
Practice 5.6 // Use of finally in try-catch // class FinallyDemo { public static void main (String [ ] args ) { int i = 0; String greetings [ ] = { "Hello Twinkle !", "Hello Java !", "Hello World ! " }; while ( i Find out the types of exceptions.
Practice 5.7 // File Name BankDemo.java public class BankDemo { public static void main(String [] args) { CheckingAccount c = new CheckingAccount(101); System.out.println("Depositing $500..."); c.deposit(500.00); try { System.out.println("\nWithdrawing $100..."); c.withdraw(100.00); System.out.println("\nWithdrawing $600..."); c.withdraw(600.00); }catch(InsufficientFundsException e) { System.out.println("Sorry, but you are short $"+ e.getAmount()); e.printStackTrace(); } } } // File Name CheckingAccount.java //create a separate class file and name it as CheckingAccount.java. Then paste the following class //contents there. public class CheckingAccount { private double balance; private int number; public CheckingAccount(int number) { this.number = number; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) throws InsufficientFundsException { if(amount Find out the types of exceptions.
Practice 5.8 import java.io.*; public class exceptionHandle{ public static void main(String[] args) throws Exception{ try{ int a,b; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); a = Integer.parseInt(in.readLine()); b = Integer.parseInt(in.readLine()); } catch(NumberFormatException ex){ System.out.println(ex.getMessage() + " is not a numeric value."); System.exit(0); } } } Find out the types of exceptions.
  • Separating Error Handling Code from "Regular" Code.
  • Propagating Errors Up the Call Stack.
  • Grouping Error Types and Error Differentiation.
  • List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions.
  • Unchecked exceptions: All Exceptions that extend the RuntimeException class are unchecked exceptions. Class Error and its subclasses also are unchecked.

The Java Interview Prep Handbook – 50 Questions Solved + Code Examples

Vahe Aslanyan

If you're trying to get a job in big tech or you want to refine your skills in software development, a strong grasp of Java is indispensable.

Java is well-known for its robustness in Object-Oriented Programming (OOP), and it provides a comprehensive foundation essential for developers at every level.

This handbook offers a detailed pathway to help you excel in Java interviews. It focuses on delivering insights and techniques relevant to roles in esteemed big tech companies, ensuring you're well-prepared for the challenges ahead.

This guide serves as a comprehensive Java review tutorial, bridging the gap between foundational Java knowledge and the sophisticated expertise sought by industry leaders like Google. And it'll help you deepen your understanding and practical application of Java, preparing you for professional success in the tech industry.

Table of Contents

  • What is Java?
  • What's the difference between the JDK, JRE, and JVM?
  • How does the 'public static void main(String[] args)' method work?
  • What is bytecode in Java?
  • Differentiate between overloading and overriding
  • What is the Java ClassLoader?
  • Can we override static methods in Java?
  • How does the 'finally' block differ from the 'finalize' method in Java?
  • What is the difference between an abstract class and an interface?
  • Explain the concept of Java packages
  • What are Java annotations?
  • How does multi-threading work in Java?
  • Use throw to raise an exception
  • Use throws to declare exceptions
  • What is the significance of the transient keyword?
  • How do you ensure thread safety in Java?
  • Explain the Singleton pattern
  • What are Java Streams?
  • What are the primary differences between ArrayList and LinkedList?
  • How do HashSet, LinkedHashSet, and TreeSet differ?
  • Differentiate between HashMap and ConcurrentHashMap
  • Describe the contract between hashCode() and equals() methods
  • What is Java reflection?
  • How do you create a custom exception in Java?
  • What is the difference between a checked and unchecked exception?
  • What are generics? Why are they used?
  • Explain the concept of Java Lambda Expressions
  • What is the diamond problem in inheritance?
  • Describe the difference between fail-fast and fail-safe iterators
  • What is type erasure in Java generics?
  • Describe the differences between StringBuilder and StringBuffer
  • What is the volatile keyword in Java?
  • Explain the Java memory model
  • What is the purpose of the default keyword in interfaces?
  • How does switch differ in Java 7 and Java 8?
  • Explain the concept of Autoboxing and Unboxing
  • Describe the @FunctionalInterface annotation
  • How can you achieve immutability in Java?
  • What is the decorator pattern?
  • Explain the Java I/O streams
  • How does the garbage collector work in Java?
  • What are the benefits of using Java NIO?
  • Explain the Observer pattern
  • What is the purpose of Java's Optional?
  • Explain Java's try-with-resources
  • Explain the difference between C++ and Java
  • What is polymorphism? Provide an example
  • How can you avoid memory leaks in Java?
  • Explain the purpose of Java's synchronized block
  • Explain the concept of modules in Java

image-23

1. What is Java?

Java is a high-level, object-oriented programming language known for its platform independence. It allows developers to write code once and run it anywhere using the Java Virtual Machine (JVM).

2. What's the Difference between the JDK, JRE, and JVM?

  • JDK (Java Development Kit): This is a software package that provides developers with the tools and utilities necessary to develop, compile, and run Java applications.
  • JRE (Java Runtime Environment): A subset of the JDK, the JRE contains the essential components, including the JVM, to run Java applications but not to develop them.
  • JVM (Java Virtual Machine): An abstract computing machine, the JVM enables Java bytecode to be executed, providing the platform independence Java is known for.

3. How Does the public static void main(String[] args) Method Work?

This method is the entry point for Java applications. The public modifier means it's accessible from other classes, static denotes it's a class-level method, and void indicates it doesn't return any value. The argument String[] args allows command-line arguments to be passed to the application.

4. What is bytecode in Java?

Bytecode is an intermediate, platform-independent code that Java source code is compiled into. It is executed by the JVM, enabling the "write once, run anywhere" capability.

5. Differentiate between overloading and overriding

  • Overloading: This occurs when two or more methods in the same class share the same name but have different parameters. It's a compile-time concept.
  • Overriding: In this case, a subclass provides a specific implementation for a method already defined in its superclass. It's a runtime concept.

image-24

6. What is the Java ClassLoader?

The Java ClassLoader is a part of the JRE that dynamically loads Java classes into the JVM during runtime. It plays a crucial role in Java's runtime environment by extending the core Java classes.

7. Can We Override Static Methods in Java?

No, we cannot override static methods. While a subclass can declare a method with the same name as a static method in its superclass, this is considered method hiding, not overriding.

8. How Does the finally Block Differ from the finalize Method in Java?

Understanding the distinction between the finally block and the finalize method in Java is crucial for effective resource management and exception handling in your programs.

Finally Block:

  • Purpose and Usage: The finally block is a key component of Java's exception handling mechanism. It is used in conjunction with try-catch blocks.
  • Execution Guarantee: Regardless of whether an exception is thrown or caught within the try or catch blocks, the code within the finally block is always executed. This ensures that it runs even if there’s a return statement in the try or catch block.
  • Common Uses: It is typically utilized for cleaning up resources, such as closing file streams, database connections, or releasing any system resources that were acquired in the try block. This helps in preventing resource leaks.

Finalize Method:

  • Definition: The finalize method is a protected method of the Object class in Java. It acts as a final resort for objects garbage collection.
  • Garbage Collector Call: It is called by the garbage collector on an object when the garbage collector determines that there are no more references to the object. However, its execution is not guaranteed, and it's generally unpredictable when, or even if, the finalize method will be invoked.
  • Resource Release: The finalize method is designed to allow an object to clean up its resources before it is collected by the garbage collector. For example, it might be used to ensure that an open file owned by an object is closed.
  • Caution in Use: It's important to note that relying on finalize for resource cleanup is generally not recommended due to its unpredictability and potential impact on performance.

Access Modifiers in Java:

  • Private: This modifier makes a member accessible only within its own class. Other classes cannot access private members of a different class.
  • Default (no modifier): When no access modifier is specified, the member has package-level access. This means it is accessible to all classes within the same package.
  • Protected: A protected member is accessible within its own package and also in subclasses. This is often used in inheritance.
  • Public: Public members are accessible from any class in the Java program. It provides the widest level of access.

Understanding these distinctions and access levels is vital for effective Java programming, ensuring resource management, security, and encapsulation are handled appropriately in your software development endeavors.

9. What is the Difference between an Abstract Class and an Interface?

An abstract class in Java is used as a base for other classes. It can contain both abstract methods (without an implementation) and concrete methods (with an implementation).

Abstract classes can have member variables that can be inherited by subclasses. A class can extend only one abstract class due to Java's single inheritance property.

Example of an Abstract Class:

An interface in Java, on the other hand, is a completely "abstract class" that is used to group related methods with empty bodies.

From Java 8 onwards, interfaces can have default and static methods with a body. A class can implement any number of interfaces.

Example of an Interface:

Both abstract classes and interfaces are foundational concepts in Java, used for achieving abstraction and supporting design patterns like Strategy and Adapter. The use of these concepts depends on the specific requirements and design considerations of your software project.

image-25

10. Explain the Concept of Java Packages

Java packages are a way of organizing and structuring classes and interfaces in Java applications. They provide a means to group related code together. Packages help prevent naming conflicts, enhance code readability, and facilitate code reusability.

For example, consider a banking application. You might have packages like com.bank.accounts , com.bank.customers , and com.bank.transactions . These packages contain classes and interfaces specific to their respective functionalities.

In essence, Java packages are like directories or folders in a file system, organizing code and making it more manageable.

11. What are Java Annotations?

Java annotations are metadata that can be added to Java source code. They provide information about the code to the compiler or runtime environment. Annotations do not directly affect the program's functionality – instead, they convey instructions to tools or frameworks.

A common use of annotations is for marking classes or methods as belonging to a specific framework or for providing additional information to tools like code analyzers, build tools, or even custom code generators.

For example, the @Override annotation indicates that a method is intended to override a method from a superclass, helping catch coding errors during compilation. Another example is @Deprecated , which indicates that a method or class is no longer recommended for use.

12. How Does Multi-threading Work in Java?

Multi-threading in Java allows a program to execute multiple threads concurrently. Threads are lightweight processes within a program that can run independently. Java provides a rich set of APIs and built-in support for multi-threading.

Threads in Java are typically created by either extending the Thread class or implementing the Runnable interface. Once created, threads can be started using the start() method, causing them to run concurrently.

Java's multi-threading model ensures that threads share resources like memory and CPU time efficiently while providing mechanisms like synchronization and locks to control access to shared data.

Multi-threading is useful for tasks such as improving application responsiveness, utilizing multi-core processors, and handling concurrent operations, as often seen in server applications.

13. Use throw to Raise an Exception

In Java programming, the throw keyword is crucial for handling exceptions deliberately and responsively. This approach to exception management allows developers to enforce specific conditions in their code and maintain control over the program flow.

In this example, an IllegalArgumentException is thrown if the age parameter is less than 18. This method of raising an exception ensures that the program behaves predictably under defined conditions, enhancing both the security and reliability of the code.

14. Use throws to Declare Exceptions

The throws keyword in Java serves to declare that a method may cause an exception to be thrown. It signals to the method's caller that certain exceptions might arise, which should be either caught or further declared.

In this scenario, the readDocument method declares that it might throw a FileNotFoundException . This declaration requires the caller of this method to handle this exception, ensuring that appropriate measures are in place to deal with potential errors, and thus improving the robustness of the application.

Both throw and throws are integral to managing exceptions in Java. throw is used for actively raising an exception in the code, while throws declares possible exceptions that a method might produce, thereby mandating their handling by the caller. This distinction is essential for writing error-resistant and well-structured Java programs.

image-26

15. What is the Significance of the transient Keyword?

The transient keyword in Java is used to indicate that a field should not be serialized when an object of a class is converted to a byte stream (for example, when using Java Object Serialization).

This is significant when you have fields in a class that you do not want to include in the serialized form, perhaps because they are temporary, derived, or contain sensitive information.

16. How Do You Ensure Thread Safety in Java?

Thread safety in Java is achieved by synchronizing access to shared resources, ensuring that multiple threads can't simultaneously modify data in a way that leads to inconsistencies or errors.

You can ensure thread safety through synchronization mechanisms like synchronized blocks, using thread-safe data structures, or utilizing concurrent utilities from the java.util.concurrent package.

In the code above, we have a SharedCounter class with a synchronized increment method, ensuring that only one thread can increment the count variable at a time. This synchronization mechanism prevents data inconsistencies when multiple threads access and modify the shared count variable.

We create two threads ( thread1 and thread2 ) that concurrently increment the counter. By using synchronized methods or blocks, we guarantee thread safety, and the final count will be accurate, regardless of thread interleaving.

17. Explain the Singleton Pattern

The Singleton pattern is a design pattern that ensures a class has only one instance and provides a global point of access to that instance. It is achieved by making the constructor of the class private, creating a static method to provide a single point of access to the instance, and lazily initializing the instance when needed.

Implementation without Singleton:

Let's imagine a scenario where you want to establish a database connection. Without the Singleton pattern, every time you'd need a connection, you might end up creating a new one.

Now, imagine initializing this connection multiple times in different parts of your application:

For the above code, "Establishing a new database connection..." would be printed twice, implying two separate connections were created. This is redundant and can be resource-intensive.

Implementation with Singleton:

With the Singleton pattern, even if you attempt to get the connection multiple times, you'd be working with the same instance.

Initializing this connection multiple times:

For the above code, "Establishing a single database connection..." would be printed just once, even though we've called getInstance() twice.

18. What are Java Streams?

Java Streams are a powerful abstraction for processing sequences of elements, such as collections, arrays, or I/O channels, in a functional and declarative style. They provide methods for filtering, mapping, reducing, and performing various transformations on data.

Streams can significantly simplify code and improve readability when working with data collections.

19. What Are the Primary Differences between ArrayList and LinkedList?

ArrayList and LinkedList are both implementations of the List interface. The primary differences between them lie in their internal data structures.

ArrayList uses a dynamic array to store elements, offering fast random access but slower insertions and deletions. LinkedList uses a doubly-linked list, which provides efficient insertions and deletions but slower random access.

image-27

20. How do HashSet , LinkedHashSet , and TreeSet Differ?

  • HashSet stores elements in an unordered manner, offering constant-time complexity for basic operations.
  • LinkedHashSet maintains the order of insertion, providing ordered iteration of elements.
  • TreeSet stores elements in a sorted order (natural or custom), offering log(n) time complexity for basic operations.

In this code, we add a large number of elements to each type of set ( HashSet , LinkedHashSet , and TreeSet ) and measure the time it takes to perform this operation. This demonstrates the performance characteristics of each set type.

Typically, you will observe that HashSet performs the fastest for adding elements since it doesn't maintain any specific order, followed by LinkedHashSet , and TreeSet , which maintains a sorted order.

This output demonstrates the time taken (in nanoseconds) to add one million elements to each of the three sets: HashSet , LinkedHashSet , and TreeSet . As you can see, HashSet is the fastest, followed by LinkedHashSet , and TreeSet is the slowest due to its need to maintain elements in sorted order.

21. Differentiate between HashMap and ConcurrentHashMap

HashMap is not thread-safe and is suitable for single-threaded applications. ConcurrentHashMap , on the other hand, is designed for concurrent access and supports multiple threads without external synchronization. It provides high concurrency and performance for read and write operations.

22. Describe the Contract between the hashCode() and equals() Methods

The contract between hashCode() and equals() methods states that if two objects are equal ( equals() returns true), their hash codes ( hashCode() ) must also be equal.

However, the reverse is not necessarily true: objects with equal hash codes may not be equal. Adhering to this contract is crucial when using objects as keys in hash-based collections like HashMap .

23. What is Java Reflection?

Java reflection is a feature that allows you to inspect and manipulate the metadata of classes, methods, fields, and other program elements at runtime. It enables you to perform tasks such as dynamically creating objects, invoking methods, and accessing fields, even for classes that were not known at compile time.

24. How Do You Create a Custom Exception in Java?

You can create a custom exception in Java by extending the Exception class or one of its subclasses. By doing so, you can define your exception with specific attributes and behaviors tailored to your application's needs.

image-28

25. What is the Difference between a Checked and Unchecked Exception?

Checked exceptions are exceptions that must be either caught using a try-catch block or declared in the method signature using the throws keyword.

Unchecked exceptions (usually subclasses of RuntimeException ) do not require such handling.

Checked exceptions are typically used for recoverable errors, while unchecked exceptions represent programming errors or runtime issues.

Here is a code example to illustrate checked and unchecked exceptions.

In this code, we attempt to read a file using FileReader, which may throw a checked exception called IOException .

To handle this exception, we enclose the file reading code in a try-catch block specifically catching IOException . This is an example of how you handle checked exceptions, which are typically used for recoverable errors like file not found or I/O issues.

Now, let's take a look at an example of an unchecked exception:

In this code, we attempt to divide an integer by zero, which leads to an unchecked exception called ArithmeticException . Unchecked exceptions do not require explicit handling using a try-catch block. However, it's good practice to catch and handle them when you anticipate such issues. These exceptions often represent programming errors or runtime issues.

26. What Are Generics? Why Are They Used?

Generics in Java are a powerful feature that allows you to create classes, interfaces, and methods that operate on types. They provide a way to define classes or methods with a placeholder for the data type that will be used when an instance of the class is created or when a method is called.

Generics are used to make your code more reusable, type-safe, and less error-prone by allowing you to write generic algorithms that work with different data types. They help eliminate the need for typecasting and enable compile-time type checking.

For example, consider the use of a generic class to create a List of integers:

Generics ensure that you can only add integers to the list and that you don't need to perform explicit typecasting when retrieving elements from the list.

27. Explain the Concept of Java Lambda Expressions

Lambda expressions in Java are a concise way to express instances of single-method interfaces (functional interfaces) using a more compact syntax. They facilitate functional programming by allowing you to treat functions as first-class citizens.

Lambda expressions consist of a parameter list, an arrow (->), and a body. They provide a way to define and use anonymous functions.

For example, consider a functional interface Runnable that represents a task to be executed. With a lambda expression, you can define and execute a runnable task as follows:

We will talk about a more practical example later down the post.

28. What is the Diamond Problem in Inheritance?

The diamond problem in inheritance is a common issue in object-oriented programming languages that support multiple inheritance. It occurs when a class inherits from two classes that have a common ancestor class, resulting in ambiguity about which superclass's method or attribute to use.

Java solves the diamond problem by not supporting multiple inheritance of classes (that is, a class cannot inherit from more than one class).

But Java allows multiple inheritance of interfaces, which doesn't lead to the diamond problem because interfaces only declare method signatures, and the implementing class must provide concrete implementations. In case of method conflicts, the implementing class must explicitly choose which method to use.

Here's a simplified example to illustrate the diamond problem (even though Java doesn't directly encounter it):

In Java, the diamond problem is avoided through interface implementation and explicit method choice when conflicts arise.

29. Describe the Difference between Fail-fast and Fail-safe Iterators

In Java, fail-fast and fail-safe are two strategies for handling concurrent modification of collections during iteration.

Fail-fast iterators throw a ConcurrentModificationException if a collection is modified while being iterated. Fail-safe iterators, on the other hand, do not throw exceptions and allow safe iteration even if the collection is modified concurrently.

Fail-Fast Iterator Example:

In this example, when we attempt to remove an element from the list while iterating, it leads to a ConcurrentModificationException , which is characteristic of fail-fast behavior. Fail-fast iterators immediately detect and throw an exception when they detect that the collection has been modified during iteration.

Fail-Safe Iterator Example:

In this example, a ConcurrentHashMap is used, which supports fail-safe iterators. Even if we modify the map concurrently while iterating, there is no ConcurrentModificationException thrown. Fail-safe iterators continue iterating over the original elements and do not reflect changes made after the iterator is created.

image-29

30. What is Type Erasure in Java Generics?

Type erasure is a process in Java where type parameters in generic classes or methods are replaced with their upper bound or Object during compilation. This erasure ensures backward compatibility with pre-generic Java code. But it means that the type information is not available at runtime, which can lead to issues in some cases.

31. Describe the Differences between StringBuilder and StringBuffer

Thread safety:.

StringBuffer is thread-safe. This means it is synchronized, so it ensures that only one thread can modify it at a time. This is crucial in a multithreaded environment where you have multiple threads modifying the same string buffer.

StringBuilder , on the other hand, is not thread-safe. It does not guarantee synchronization, making it unsuitable for use in scenarios where a string is accessed and modified by multiple threads concurrently. But this lack of synchronization typically leads to better performance under single-threaded conditions.

Performance:

Because StringBuffer operations are synchronized, they involve a certain overhead that can impact performance negatively when high-speed string manipulation is required.

StringBuilder is faster than StringBuffer because it avoids the overhead of synchronization. It's an excellent choice for string manipulation in a single-threaded environment.

Use Case Scenarios:

Use StringBuffer when you need to manipulate strings in a multithreaded environment. Its thread-safe nature makes it the appropriate choice in this scenario.

Use StringBuilder in single-threaded situations, such as local method scope or within a block synchronized externally, where thread safety is not a concern. Its performance benefits shine in these cases.

API Similarity:

Both StringBuilder and StringBuffer have almost identical APIs. They provide similar methods for manipulating strings, such as append() , insert() , delete() , reverse() , and so on.

This similarity means that switching from one to the other in your code is generally straightforward.

Memory Efficiency:

Both classes are more memory efficient compared to using String for concatenation. Since String is immutable in Java, concatenation with String creates multiple objects, whereas StringBuilder and StringBuffer modify the string in place.

Introduced Versions:

StringBuffer has been a part of Java since version 1.0, whereas StringBuilder was introduced later in Java 5. This introduction was primarily to offer a non-synchronized alternative to StringBuffer for improved performance in single-threaded applications.

You should make the choice between StringBuilder and StringBuffer based on the specific requirements of your application, particularly regarding thread safety and performance needs.

While StringBuffer provides safety in a multithreaded environment, StringBuilder offers speed and efficiency in single-threaded or externally synchronized scenarios.

32. What is the volatile Keyword in Java?

Basic Definition: The volatile keyword is used to modify the value of a variable by different threads. It ensures that the value of the volatile variable will always be read from the main memory and not from the thread's local cache.

Visibility Guarantee: In a multithreading environment, threads can cache variables. Without volatile, there's no guarantee that one thread's changes to a variable will be visible to another. The volatile keyword guarantees visibility of changes to variables across threads.

Happens-Before Relationship: volatile establishes a happens-before relationship in Java. This means that all the writes to the volatile variable are visible to subsequent reads of that variable, ensuring a consistent view of the variable across threads.

Usage Scenarios: volatile is used for variables that may be updated by multiple threads. It's often used for flags or status variables. For example, a volatile boolean running variable can be used to stop a thread.

Limitations: Volatile cannot be used with class or instance variables. It's only applicable to fields. It doesn't provide atomicity.

For instance, volatile int i; i++; is not an atomic operation. For atomicity, you might need to resort to AtomicInteger or synchronized methods or blocks. It's not a substitute for synchronization in every case, especially when multiple operations on the volatile variable need to be atomic.

Avoiding Common Misconceptions: A common misconception is that volatile makes the whole block of statements atomic, which is not true. It only ensures the visibility and ordering of the writes to the volatile variable.

Another misconception is that volatile variables are slow. But while they might have a slight overhead compared to non-volatile variables, they are generally faster than using synchronized methods or blocks. Performance Considerations: volatile can be a more lightweight alternative to synchronization in cases where only visibility concerns are present. It doesn't incur the locking overhead that synchronized methods or blocks do. Best Practices: Use volatile sparingly and only when necessary. Overusing it can lead to memory visibility issues that are harder to detect and debug. Always assess whether your use case requires atomicity, in which case other concurrent utilities or synchronization might be more appropriate.

volatile use case:

We will create a simple program where one thread modifies a volatile boolean flag, and another thread reads this flag. This flag will be used to control the execution of the second thread.

Code Example:

Key points in the comments:.

  • Visibility of volatile variable: The most crucial aspect of using volatile here is ensuring that the update to the running variable in one thread (main thread) is immediately visible to another thread ( thread1 ). This is what allows thread1 to stop gracefully when running is set to false .
  • Use in a Simple Flag Scenario: The example demonstrates a common scenario for using volatile , that is as a simple flag to control the execution flow in a multithreaded environment.
  • Absence of Compound Operations: Note that we are not performing any compound operations (like incrementing) on the running variable. If we were, additional synchronization would be needed because volatile alone does not guarantee atomicity of compound actions.
  • Choice of volatile Over Synchronization: The choice to use volatile over other synchronization mechanisms (like synchronized blocks or Locks ) is due to its lightweight nature when dealing with the visibility of a single variable. It avoids the overhead associated with acquiring and releasing locks.

33. Explain the Java Memory Model

The JMM defines how Java threads interact through memory. Essentially, it describes the relationship between variables and the actions of threads (reads and writes), ensuring consistency and predictability in concurrent programming.

Happens-Before Relationship:

At the heart of the JMM is the 'happens-before' relationship. This principle ensures memory visibility, guaranteeing that if one action happens-before another, then the first is visible to and affects the second.

For example, changes to a variable made by one thread are guaranteed to be visible to other threads only if a happens-before relationship is established.

Memory Visibility:

Without the JMM, threads might cache variables, and changes made by one thread might not be visible to others. The JMM ensures that changes made to a shared variable by one thread will eventually be visible to other threads.

Synchronization:

The JMM utilizes synchronization to establish happens-before relationships. When a variable is accessed within synchronized blocks, any write operation in one synchronized block is visible to any subsequent read operation in another synchronized block.

Additionally, the JMM governs the behavior of volatile variables, ensuring visibility of updates to these variables across threads without synchronization.

Thread Interleaving and Atomicity:

The JMM defines how operations can interleave when executed by multiple threads. This can lead to complex states if not managed correctly.

Atomicity refers to operations that are indivisible and uninterrupted. In Java, operations on most primitive types (except long and double ) are atomic. However, compound operations (like incrementing a variable) are not automatically atomic.

Reordering:

The JMM allows compilers to reorder instructions for performance optimization as long as happens-before guarantees are maintained. However, this can lead to subtle bugs if not properly understood.

Use of Volatile Keyword:

The volatile keyword plays a significant role in the JMM. It ensures that any write to a volatile variable establishes a happens-before relationship with subsequent reads of that variable, thus ensuring memory visibility without the overhead of synchronization.

Locking Mechanisms:

Locks in Java (implicit via synchronized blocks/methods or explicit via ReentrantLock or others) also adhere to the JMM, ensuring that memory visibility is maintained across threads entering and exiting locks.

Safe Publication:

The JMM also addresses the concept of safe publication, ensuring that objects are fully constructed and visible to other threads after their creation.

High-Level Implications:

Understanding the JMM is critical for writing correct and efficient multi-threaded Java applications. It helps developers reason about how shared memory is handled, especially in complex applications where multiple threads interact and modify shared data.

Best Practices:

  • Always use the appropriate synchronization mechanism to ensure memory visibility and atomicity.
  • Be cautious about memory visibility issues; even simple operations can lead to visibility problems in a multi-threaded context.
  • Understand the cost of synchronization and use volatile variables where appropriate.

34. What is the Purpose of the default Keyword in Interfaces?

The default keyword in Java interfaces, introduced in Java 8, marks a significant evolution in the Java language, especially in how interfaces are used and implemented. It serves several key purposes:

Adding Method Implementations in Interfaces:

Prior to Java 8, interfaces in Java could only contain method signatures (abstract methods) without any implementation.

The default keyword allows you to provide a default implementation for a method within an interface. This feature bridges a gap between full abstraction (interfaces) and concrete implementations (classes).

Enhancing Interface Evolution:

One of the primary motivations for introducing the default keyword was to enhance the evolution of interfaces.

Before Java 8, adding a new method to an interface meant breaking all its existing implementations. With default methods, you can add new methods to interfaces with default implementations without breaking the existing implementations.

This is particularly useful for library designers, ensuring backward compatibility when interfaces need to be expanded.

Facilitating Functional Programming:

\The introduction of default methods played a crucial role in enabling functional programming features in Java, such as Lambda expressions. It allowed for richer interfaces (like java.util.stream.Stream ) which are fundamental to functional-style operations in Java.

Multiple Inheritance of Behavior:

While Java does not allow multiple inheritance of state (that is, you cannot inherit from multiple classes), the default keyword enables multiple inheritance of behavior.

A class can implement multiple interfaces, and each interface can provide a default implementation of methods, which the class inherits.

Reducing Boilerplate Code:

default methods can be used to reduce the amount of boilerplate code by providing a general implementation that can be shared across multiple implementing classes, while still allowing individual classes to override the default implementation if a more specific behavior is required.

Example Usage:

In this example, any class implementing the Vehicle interface must provide an implementation for cleanVehicle , but it's optional for startEngine . The default implementation of startEngine can be used as is, or overridden by the implementing class.

Best Practices and Considerations:

  • Use Sparingly: Default methods should be used judiciously. They are best suited for gradually evolving interfaces or for methods that have a common implementation across most implementing classes.
  • Design With Care: When designing interfaces with default methods, consider how they might be used or overridden. It's important to document the expected behavior and interactions between default methods and other abstract methods in the interface.
  • Overriding Default Methods: Just like any inherited method, default methods can be overridden in the implementing class. This should be done to provide a specific behavior different from the default implementation.

image-30

35. How Does switch Differ in Java 7 and Java 8?

Limited Case Types: In Java 7, the switch statement supports limited types for the case labels, namely byte , short , char , int , and their corresponding Wrapper classes, along with enum types and, as of Java 7, String .

Traditional Structure: The structure of the switch statement in Java 7 follows the conventional C-style format, with a series of case statements and an optional default case. Each case falls through to the next unless it ends with a break statement or other control flow statements like return .

No Lambda Expressions: Java 7 does not support lambda expressions, and thus, they cannot be used within a switch statement or case labels.

Lambda Expressions: While the basic syntax and supported types for the switch statement itself did not change in Java 8, the introduction of lambda expressions in this version brought a new paradigm in handling conditional logic.

This doesn’t directly change how switch works, but it offers alternative patterns for achieving similar outcomes, especially when used in conjunction with functional interfaces.

Functional Programming Approach: Java 8 promotes a more functional programming style, encouraging the use of streams, lambda expressions, and method references. This can lead to alternatives for traditional switch statements, like using Map of lambdas for conditional logic, which can be more readable and concise.

Enhanced Readability and Maintainability: Although not a direct change to the switch statement, the use of lambda expressions and functional programming practices in Java 8 can lead to more readable and maintainable code structures that might otherwise use complex switch or nested if-else statements.

Practical Considerations:

  • When to Use switch in Java 8: Despite the advancements in Java 8, the switch statement remains a viable and efficient method for controlling complex conditional logic. It is particularly useful when dealing with a known set of possible values, such as enum constants or strings.
  • Combining switch with Lambdas: While you cannot use lambdas directly in a switch statement, Java 8 allows for more elegant ways to handle complex conditional logic that might traditionally have been a use case for switch . For example, using a Map with lambdas or method references can sometimes replace a complex switch statement.
  • Performance Considerations: The performance of a switch statement is generally better than a series of if-else statements, especially when dealing with a large number of cases, due to its internal implementation using jump tables or binary search.

36. Explain the Concept of Autoboxing and Unboxing

What is autoboxing.

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer , a double to a Double , and so on.

When to use autoboxing

This feature is commonly used when working with collections, like ArrayList or HashMap , which can only store objects and not primitive types.

It simplifies the code by allowing direct assignment of a primitive value to a variable of the corresponding wrapper class.

Behind the Scenes:

When autoboxing, the compiler essentially uses the valueOf method of the respective wrapper class to convert the primitive to its wrapper type.

For example, Integer.valueOf(int) is used for converting int to Integer .

Performance Considerations:

  • While convenient, autoboxing can introduce performance overhead, especially in scenarios with extensive boxing and unboxing in tight loops, due to the creation of additional objects.

What is unboxing?

Unboxing is the reverse process, where the Java compiler automatically converts an object of a wrapper type to its corresponding primitive type.

When to use unboxing

It is often used when performing arithmetic operations or comparisons on objects of wrapper classes, where primitive types are required.

During unboxing, the compiler uses the corresponding wrapper class's method to extract the primitive value. For instance, it uses Integer.intValue() to get the int from an Integer .

Null Pointer Exception:

A crucial point to consider is that unboxing a null object reference will throw a NullPointerException . This is a common bug in code that relies heavily on autoboxing and unboxing.

  • Be Aware of Implicit Conversions: It's important to be aware that these conversions are happening, as they can sometimes lead to unexpected behavior, especially with regards to NullPointerExceptions during unboxing of null references.
  • Consider Performance: In performance-sensitive applications, prefer using primitives to avoid the overhead of autoboxing and unboxing.
  • Null Safety: Always check for null before unboxing, to avoid potential NullPointerExceptions .
  • Readability vs Efficiency: While autoboxing and unboxing significantly improve code readability and reduce boilerplate, be mindful of their impact on performance and choose wisely based on the application's context.

37. Describe the @FunctionalInterface Annotation

The @FunctionalInterface annotation in Java is a key feature that dovetails with the language's embrace of functional programming concepts, particularly since Java 8. It serves a specific purpose in defining and enforcing certain coding patterns, making it a vital tool for developers focusing on functional-style programming.

Definition and Purpose

@FunctionalInterface is an annotation that marks an interface as a functional interface.

A functional interface in Java is an interface that contains exactly one abstract method. This restriction makes it eligible to be used in lambda expressions and method references, which are core components of Java's functional programming capabilities.

Enforcing Single Abstract Method

The primary role of @FunctionalInterface is to signal the compiler to enforce the rule of a single abstract method. If the annotated interface does not adhere to this rule, the compiler throws an error, ensuring the interface's contract is not accidentally broken by adding additional abstract methods.

Usage and Implications:

  • Lambda Expressions: Functional interfaces provide target types for lambda expressions and method references. For example, Java's standard java.util.function package contains several functional interfaces like Function<T,R> , Predicate<T> , Consumer<T> , which are widely used in stream operations and other functional programming scenarios.
  • Optional but Recommended: While the @FunctionalInterface annotation is not mandatory for an interface to be considered a functional interface by the Java compiler, using it is considered best practice. It makes the developer's intention clear and ensures the contract of the functional interface is not inadvertently broken.
  • Existing Interfaces: Many existing interfaces from earlier versions of Java naturally fit the definition of a functional interface. For example, java.lang.Runnable and java.util.concurrent.Callable are both functional interfaces as they have only one abstract method.

In this example, SimpleFunction is a functional interface with one abstract method execute() . The @FunctionalInterface annotation ensures that no additional abstract methods are inadvertently added.

  • Clarity and Documentation: Use @FunctionalInterface to communicate your intention clearly both to the compiler and to other developers. It serves as a form of documentation.
  • Design with Care: When designing a functional interface, consider its general utility and how it fits into the broader application architecture, especially if it's intended to be used across different parts of the application.
  • Avoid Overuse: While functional programming in Java can lead to more elegant and concise code, be cautious of overusing lambdas and functional interfaces, as they can make the code harder to read and debug if used excessively or inappropriately.
  • Compatibility with Older Java Versions: Be aware that @FunctionalInterface is a Java 8 feature. If you're working on applications that need to be compatible with earlier Java versions, you won’t be able to use this feature.

38. How Can You Achieve Immutability in Java?

Achieving immutability in Java is a fundamental practice, particularly useful for creating robust, thread-safe applications.

An immutable object is one whose state cannot be modified after it is created. Here's a detailed and precise explanation of how to achieve immutability in Java:

Core Principles of Immutability:

  • No Setters: Immutable objects do not expose any methods to modify their state after construction. This typically means not providing any setter methods.
  • Final Class: The class should be declared as final to prevent subclassing. Subclasses could add mutable state, undermining the immutability of the parent class.
  • Final Fields: All fields should be final , ensuring they are assigned only once, typically within the constructor, and cannot be re-assigned.
  • Private Fields: Fields should be private to prevent external modification and to encapsulate the data.
  • No Direct Access to Mutable Objects:
  • If your class has fields that are references to mutable objects (like arrays or collections), ensure these fields are not directly exposed or modified:
  • Do not provide methods that modify mutable objects.
  • Do not share references to the mutable objects. Provide copies of mutable objects when needed.

How to Create an Immutable Class:

  • Defensive Copies: When dealing with mutable objects passed to the constructor or returned by methods, create defensive copies. This practice prevents external code from modifying the internal state of the immutable object.
  • Immutable Collections: Utilize immutable collections (like those provided in Java 9 and later) to simplify the creation of classes with immutable collection fields.
  • Performance Considerations: Be mindful of the performance implications of creating defensive copies, especially in performance-critical applications.
  • Use in Multi-threaded Environments: Immutable objects are inherently thread-safe, making them ideal for use in multi-threaded environments.
  • String and Wrapper Types: Leverage the immutability of String and wrapper types (Integer, Long, and so on) as part of your immutable objects.
  • Design Strategy: Consider immutability as a design strategy, especially for objects representing values that are not expected to change, such as configuration data, constants, or natural data types.

Advantages of Immutability:

  • Simplicity and Clarity: Immutable objects are easier to understand and use. There's no need to track changes in state, reducing cognitive load.
  • Thread Safety: Immutability eliminates issues related to concurrency and synchronization, as immutable objects can be freely shared between threads without synchronization.
  • Caching and Reuse: Immutable objects can be cached and reused, as they are guaranteed not to change, reducing the overhead of object creation.
  • Hashcode Caching: Immutable objects are great candidates for caching their hashcode, which can be beneficial in collections like HashMaps and HashSets .

39. What is the Decorator Pattern?

The Decorator Pattern is a structural design pattern used in object-oriented programming, and it's particularly useful for extending the functionality of objects at runtime. It is a robust alternative to subclassing, providing a more flexible approach to add responsibilities to objects without modifying their underlying classes.

Purpose of decorator pattern

The Decorator Pattern allows you to attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

The pattern involves a set of decorator classes that are used to wrap concrete components. Each decorator class has a reference to a component object and adds its own behavior either before or after delegating the task to the component object.

How to implement the decorator pattern

It typically involves an abstract decorator class that implements or extends the same interface or superclass as the objects it will dynamically add functionality to. Concrete decorators then extend the abstract decorator.

Key Components:

  • Component: An interface or abstract class defining the operations that can be altered by decorators.
  • Concrete Component: A class implementing or extending the Component, defining an object to which additional responsibilities can be attached.
  • Decorator: An abstract class that extends or implements the Component interface and has a reference to a Component.
  • Concrete Decorator: A class that extends the Decorator and adds functionalities to the Component it decorates.

Decorator example in Java:

Usage and advantages:.

  • Flexibility: The Decorator Pattern provides a more flexible way to add responsibilities to objects compared to subclassing. New functionalities can be added at runtime.
  • Avoid Class Explosion: It helps in avoiding an extensive hierarchy of subclasses when you need multiple combinations of functionalities.
  • Single Responsibility Principle: Decorators allow functionalities to be divided into simple classes with single responsibilities.

Considerations:

  • Complexity: Overuse of the decorator pattern can lead to complexity, making the code harder to understand and maintain.
  • Instantiation Management: Managing the instantiation of decorated objects can be challenging, especially when dealing with multiple layers of decoration.

The Decorator Pattern is a powerful tool in a software developer's toolkit, offering a dynamic and flexible solution for extending object functionality. Understanding and applying this pattern can greatly enhance the design of software, particularly in situations where adding responsibilities to objects at runtime is necessary.

This pattern is highly valued in software development, as it showcases an ability to effectively manage and extend object functionalities without altering existing codebases, aligning with principles of maintainability and scalability.

40. Explain Java I/O Streams

Java I/O (Input/Output) streams are a fundamental part of the Java I/O API, providing a robust framework for handling input and output operations in Java. Understanding these streams is crucial for efficient data handling in Java applications.

Overview of Java I/O Streams

I/O streams in Java are used to read data from an input source and to write data to an output destination. The Java I/O API is rich and provides various classes to handle different types of data, like bytes, characters, objects, etc.

Stream Types:

Java I/O streams are broadly categorized into two types:

  • Byte Streams: Handle I/O of raw binary data.
  • Character Streams: Handle I/O of character data, automatically handling character encoding and decoding.

Byte Streams:

  • Classes: InputStream and OutputStream are abstract classes at the hierarchy's root for byte streams.
  • Usage: They are used for reading and writing binary data, such as image or video files.
  • Example Classes: FileInputStream , FileOutputStream , BufferedInputStream , BufferedOutputStream , etc.

Character Streams:

  • Classes: Reader and Writer are abstract classes for character streams.
  • Usage: Suitable for handling textual data, ensuring correct interpretation of characters according to the default character encoding.
  • Example Classes: FileReader , FileWriter , BufferedReader , BufferedWriter , etc.

Key Features of Java I/O Streams:

  • Stream Hierarchy: Java uses a hierarchy of classes to manage different types of I/O operations, allowing for flexibility and reusability of code.
  • Decorators: Java I/O uses decorators, where one stream wraps another and adds additional capabilities, like buffering, data conversion, and so on.
  • Buffering: Buffering is a common practice in I/O streams to enhance I/O efficiency, allowing for the temporary storage of data in memory before it's written to or read from the actual I/O source.
  • Exception Handling: I/O operations in Java are prone to errors like file not found, access denied, etc. Hence, most I/O operations throw IOException , which must be properly handled using try-catch blocks or thrown further.
  • Use Buffered Streams: Always use buffered streams ( BufferedInputStream , BufferedOutputStream , BufferedReader , BufferedWriter ) for efficient I/O operations, as they reduce the number of actual I/O operations by buffering chunks of data.
  • Close Streams: Ensure streams are closed after their operation is complete to free up system resources. This is typically done in a finally block or using try-with-resources introduced in Java 7.
  • Error Handling: Implement robust error handling. I/O operations are susceptible to many issues, so proper exception handling is crucial.
  • Character Encoding: Be mindful of character encoding while using character streams. Incorrect handling of encoding can lead to data corruption.

Practical Example:

In this example, BufferedReader and BufferedWriter are used for reading from and writing to a text file, demonstrating the use of character streams with buffering for efficiency.

Java I/O streams form the backbone of data handling in Java applications. Understanding the distinction between byte and character streams, along with the proper use of buffering and exception handling, is essential for writing efficient, robust, and maintainable Java code.

This knowledge is vital for Java developers and is often a subject of interest in technical interviews, showcasing one's capability to handle data proficiently in Java applications.

image-31

41. How Does the Garbage Collector Work in Java?

In Java, garbage collection (GC) is a critical process of automatically freeing memory by reclaiming space from objects that are no longer in use, ensuring efficient memory management.

Understanding how the garbage collector works in Java is essential for writing high-performance applications and is a key area of knowledge in professional Java development.

Overview of Garbage Collection in Java

The primary function of garbage collection in Java is to identify and discard objects that are no longer needed by a program. This prevents memory leaks and optimizes memory usage.

Automatic Memory Management

Unlike languages where memory management is manual (like C/C++), Java provides automatic memory management through its garbage collector, which runs in the background.

How the Garbage Collector Works

Object creation and heap storage:.

In Java, objects are created in a heap memory area. This heap is divided into several parts – Young Generation, Old Generation (or Tenured Generation), and Permanent Generation (replaced by Metaspace in Java 8).

  • Young Generation: Newly created objects reside in the Young Generation, which is further divided into three parts: one Eden space and two Survivor spaces (S0 and S1). Most objects die young. When the Eden space fills up, a minor GC is triggered, moving surviving objects to one of the Survivor spaces (S0 or S1) and clearing Eden.
  • Aging of Objects: As objects survive more garbage collection cycles, they age. After surviving certain cycles, they are moved to the Old Generation.
  • Old Generation: The Old Generation stores long-living objects. A more comprehensive form of GC, known as major GC, occurs here, which is generally more time-consuming.
  • Metaspace (Java 8 and above): Metaspace stores metadata of classes. Unlike the PermGen (Permanent Generation) space in earlier Java versions, Metaspace uses native memory, and its size is not fixed but can be configured.

Types of Garbage Collectors in Java:

  • Serial GC: Suitable for single-threaded environments. It freezes all application threads during garbage collection.
  • Parallel GC: Also known as Throughput Collector, it uses multiple threads for young generation garbage collection but stops all application threads during major GC.
  • Concurrent Mark Sweep (CMS) GC: Minimizes pauses by doing most of its work concurrently with application threads but requires more CPU resources.
  • G1 Garbage Collector: Designed for large heap memory areas, it divides the heap into regions and prioritizes GC on regions with the most garbage first.

Garbage Collection Processes

The process starts by marking all reachable objects. Reachable objects are those that are accessible directly or indirectly through references from root objects (like local variables, static fields, etc.).

Unreachable objects (those not marked as reachable) are considered for deletion .

To prevent fragmentation and optimize memory usage, some garbage collectors perform compaction , moving surviving objects closer together.

  • Avoid Memory Leaks: Despite automatic garbage collection, memory leaks can still occur (for example, through static references). It's crucial to be mindful of object references and their lifecycles.
  • GC Tuning: For high-performance applications, GC tuning can be essential. Understanding different garbage collector types and their configuration parameters allows for optimal tuning according to application needs.
  • Monitoring and Profiling: Regular monitoring of garbage collection and memory usage is important, especially for applications with high throughput or large heaps.

Garbage collection in Java is a sophisticated system designed to efficiently manage memory in the Java Virtual Machine (JVM). An in-depth understanding of how garbage collection works, its types, and its impact on application performance is essential for Java developers, particularly those working on large-scale, high-performance applications.

This knowledge not only helps in writing efficient and robust applications but also is a valuable skill in troubleshooting and performance tuning, aspects highly regarded in the field of software development.

42. What Are the Benefits of Using Java NIO?

Java NIO (New Input/Output), introduced in JDK 1.4, marks a substantial advancement in Java's approach to I/O operations. It was developed to address the constraints of traditional I/O methods, leading to improved scalability and efficiency.

This makes Java NIO particularly advantageous in scenarios demanding high throughput and concurrent access.

Let’s discuss the key benefits of using Java NIO in detail.

1. Channels and Buffers: Enhanced Data Handling

  • Channels : These are bi-directional conduits allowing both reading and writing operations. Unlike traditional unidirectional streams, channels simplify I/O patterns, especially for network sockets, by enabling two-way communication within a single channel.
  • Buffers : Acting as fixed-size data containers, buffers allow batch processing of data. This is more efficient compared to the byte-by-byte processing in traditional I/O, as it enables handling data in larger, more manageable blocks.

2. Non-blocking and Asynchronous I/O

Java NIO supports non-blocking and asynchronous I/O operations, a stark contrast to the blocking nature of traditional I/O where a thread remains idle until an operation completes.

This feature of NIO means a thread can initiate an I/O operation and continue performing other tasks without waiting for the I/O process to finish. This capability significantly enhances the scalability and responsiveness of applications, making them more efficient in handling multiple concurrent I/O requests.

3. Practical Applications

Java NIO is particularly effective in environments that require high-performance and low latency, such as:

  • Web and Application Servers : Managing high-volume network traffic efficiently.
  • Real-time Systems : Like trading platforms where quick data processing is critical.
  • Big Data Applications : Benefiting from efficient handling of large datasets.
  • File-based Database Systems : Where efficient file I/O operations are crucial.

4. Channels: The Foundation of NIO’s Architecture

Channels serve as the backbone of NIO, providing a more unified and simplified interface for various I/O operations. They come in different types, each catering to specific needs:

  • FileChannel : For file operations.
  • SocketChannel and ServerSocketChannel : For TCP network communications.
  • DatagramChannel : For UDP operations.
  • Pipes : For inter-thread communication. Particularly in network operations, the ability of channels to operate in a non-blocking mode allows a single thread to handle multiple connections, enhancing the application’s scalability.

5. Buffers: Central to NIO’s Data Transfer

Buffers in NIO are essential for data transfer, acting as temporary storage for data during I/O operations. Their key operations include:

  • Put and Get : For writing and reading data.
  • Flip : To switch modes between reading and writing.
  • Clear and Compact : Preparing the buffer for new data. Different buffer types (like ByteBuffer, CharBuffer, IntBuffer) cater to various data primitives, enhancing the flexibility and efficiency of data handling. Notably, direct buffers, which are allocated outside of the JVM heap, can provide faster I/O operations, though they come with higher allocation and deallocation costs.

6. Selectors: Streamlining Scalable I/O Operations

Selectors are a unique NIO feature enabling a single thread to monitor multiple channels for readiness, thus efficiently managing numerous I/O operations. This reduces the need for multiple threads, cutting down on resource usage and context switching, which is particularly advantageous in high-performance environments.

7. Improved Performance and Scalability

The amalgamation of channels, buffers, and selectors provides a substantial performance boost. The non-blocking nature of NIO minimizes idle thread time, and managing multiple channels with a single thread significantly improves the scalability. This is pivotal in server environments dealing with numerous simultaneous connections.

Java NIO offers a robust, scalable, and efficient framework for handling I/O operations, addressing many of the limitations of traditional I/O. Its design is particularly advantageous for high-throughput and concurrent-processing systems.

While the complexity of NIO might be higher compared to traditional I/O, the performance and scalability benefits it provides make it an indispensable tool for developers working on large-scale, I/O-intensive Java applications.

43. Explain the Observer Pattern

The Observer pattern is a design pattern where an object, known as the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

It's particularly useful in the scenario where a single object needs to notify an array of objects about a change in its state. In the context of a newsletter system, the Observer pattern can be effectively used to notify subscribers whenever a new post is available.

How to Implement the Observer Pattern for a Newsletter System

Let's break down the implementation using the Observer pattern in the context of a newsletter system:

  • Subject (Newsletter) : This is the entity being observed. It will notify all attached observers when a new post is available.
  • Observer (Subscriber) : These are the observers who wish to be notified about new posts in the newsletter.
  • Client : This will use both the Subject and Observers.

Step 1: Create the Subject Class (Newsletter)

Step 2: create the observer abstract class (subscriber), step 3: create concrete observer classes.

EmailSubscriber.java

SMSSubscriber.java

Step 4: Use the Newsletter and Concrete Subscriber Objects

Step 5: output verification.

When running NewsletterSystemDemo , the output will be something like:

This output indicates that both the email and SMS subscribers are notified whenever the newsletter has a new post.

The Observer pattern provides a clean and straightforward way to implement a subscription mechanism in a newsletter system, ensuring that all subscribers are automatically updated with the latest posts.

This pattern enhances modularity and separation of concerns, making the system easier to understand, maintain, and extend.

44. Explain the Purpose of the this Keyword.

The this keyword in Java serves a very specific and useful purpose. It refers to the current instance of the class in which it is used. This is particularly valuable in scenarios where you need to distinguish between class fields (instance variables) and parameters or variables within a method that have the same name. Let's break it down:

Reference to Instance Variables: When a class’s field is shadowed by a method or constructor parameter, this can be used for referencing the class's field. For instance, in a setter method, this helps differentiate between the instance variable and the parameter passed to the method.

Calling One Constructor from Another: In a class with overloaded constructors, this can be used to call one constructor from another, avoiding code duplication.

Returning the Current Instance: Methods can return this to return the current class instance. This is often used in method chaining.

Passing the Current Instance to Another Method: this can be passed as an argument in the method call or constructor call. This is common in event handling.

Disambiguation: It eliminates ambiguity when instance variables and parameters or local variables share the same name.

image-33

45. Explain Java's try-with-resources.

Java's try-with-resources, introduced in Java 7, is a mechanism that ensures more efficient handling of resources, like files or sockets, in Java. Its primary purpose is to simplify the cleanup of resources which must be closed after their operations are completed.

Key Characteristics:

Automatic Resource Management: In try-with-resources, resources declared within the try clause are automatically closed at the end of the statement, even if exceptions are thrown. This reduces boilerplate code significantly as compared to traditional try-catch-finally blocks.

Syntax: The resources that implement java.lang.AutoCloseable or java.io.Closeable are declared and initialized within parentheses just after the try keyword.

  • Here, the BufferedReader instance is automatically closed when the try block exits, regardless of whether it exits normally or due to an exception.
  • Exception Handling: Any exception thrown by the automatic closure of resources is suppressed if an exception is thrown in the try block. These suppressed exceptions can be retrieved using Throwable.getSuppressed() method.
  • Improved Readability and Reliability: This structure enhances code readability and reliability. It reduces the risk of resource leaks, as the closing of resources is handled automatically.
  • Use in Custom Resources: Custom classes can also utilize this mechanism by implementing the AutoCloseable interface and overriding the close method.

Practical Implications:

In real-world applications, try-with-resources ensures that resources like file streams, database connections, or network sockets are closed properly, preventing resource leaks which could lead to performance issues and other bugs. It is especially valuable in large-scale applications where resource management is critical for efficiency and reliability.

46. Explain the Difference between C++ and Java.

When distinguishing between C++ and Java, it's important to understand that both are powerful programming languages with their unique characteristics and use cases.

They share some similarities, as both are object-oriented and have similar syntax (being influenced by C), but there are key differences that set them apart.

Language Nature and Design Philosophy:

C++ is a multi-paradigm language that supports both procedural and object-oriented programming. It's often chosen for system-level programming due to its efficiency and fine-grained control over memory management.

Java , on the other hand, is primarily object-oriented and designed with a simpler approach to avoid common programming errors (like pointer errors in C++). Java's design principle "Write Once, Run Anywhere" (WORA) emphasizes portability, which is achieved through the Java Virtual Machine (JVM).

Memory Management:

In C++ , memory management is manual. Programmers have direct control over memory allocation and deallocation using operators like new and delete .

Java abstracts away the complexity of direct memory management through its Automatic Garbage Collection, which periodically frees memory that's no longer in use, reducing the likelihood of memory leaks but at the cost of less control and potential overhead.

Platform Dependency and Portability:

C++ is platform-dependent. A C++ program needs to be compiled for each specific platform it's intended to run on, which can lead to more work when targeting multiple platforms.

Java is platform-independent at the source level. Java programs are compiled into bytecode, which can run on any device equipped with a JVM, making it highly portable.

Runtime and Performance:

C++ generally offers higher performance than Java. It compiles directly to machine code, which the CPU executes, resulting in faster execution suitable for performance-critical applications.

Java may have slower performance due to the added abstraction layer of the JVM. But improvements in Just-In-Time (JIT) compilers within the JVM have significantly narrowed this performance gap.

Pointers and Memory Safety:

C++ supports both pointers and references, allowing for powerful, albeit potentially risky, memory manipulation.

Java has references but does not support pointers (at least not in the traditional sense), reducing the risk of memory access errors, thereby increasing program safety.

Exception Handling:

C++ supports exception handling but does not enforce error handling (uncaught exceptions can lead to undefined behavior).

Java has a robust exception handling mechanism, requiring checked exceptions to be caught or declared in the method signature, promoting better error management practices.

Multi-Threading:

C++ has more complex approaches to multi-threading and requires careful management to ensure thread safety.

Java provides built-in support for multi-threading with synchronized methods and blocks, making concurrent programming more manageable.

Standard Template Library (STL) vs. Java Standard Library:

C++ 's STL is a powerful library that offers containers, algorithms, iterators, and so on for efficient data manipulation.

Java 's Standard Library provides a rich set of APIs, including collections, streams, networking, and so on with a focus on ease of use.

Legacy and Use Cases:

C++ is often chosen for system/software development, game development, and applications where hardware access and performance are critical.

Java is widely used in enterprise environments, web services, and Android app development due to its portability and robust libraries.

Both C++ and Java have their strengths and are chosen based on the requirements of the project.

C++ is preferred for scenarios where performance and memory control are crucial, while Java is ideal for applications where portability and ease of use are more important.

Understanding these differences is key in selecting the right language for a particular task or project, and adapting to the strengths of each can lead to more efficient and effective programming practices.

47. What is Polymorphism? Provide an Example.

Polymorphism, a fundamental concept in object-oriented programming, allows objects to be treated as instances of their parent class or interface. It’s a Greek word meaning “many shapes” and in programming, it refers to the ability of a single function or method to work in different ways based on the object it is acting upon.

There are two primary types of polymorphism: compile-time (or static) polymorphism and runtime (or dynamic) polymorphism.

Compile-Time Polymorphism : This is achieved through method overloading and operator overloading. It’s called compile-time polymorphism because the decision about which method to call is made by the compiler.

Method Overloading involves having multiple methods in the same scope, with the same name but different parameters.

In this example, the operate method is overloaded with different parameter types, allowing it to behave differently based on the type of arguments passed.

Runtime Polymorphism : This is mostly achieved through method overriding, which is a feature of inheritance in object-oriented programming. In runtime polymorphism, the method to be executed is determined at runtime.

Method Overriding involves defining a method in a subclass that has the same name, return type, and parameters as a method in its superclass.

In this example, the speak method in the subclass Dog overrides the speak method in its superclass Animal . When the speak method is called on an object of type Dog , the overridden method in the Dog class is executed, demonstrating runtime polymorphism.

Why Polymorphism is Important

  • Flexibility and Extensibility : Polymorphism allows for flexible and extensible code. You can create a more generalized code that works on the superclass type, and it automatically adapts to the specific subclass types.
  • Code Reusability : It enables the reuse of code through inheritance and the ability to override or overload methods.
  • Loose Coupling : By using polymorphic behavior, components can be designed loosely coupled, which means a change in one part of the system causes minimal or no effect on other parts of the system.
  • Simplifies Code Maintenance : With polymorphism, developers can write more maintainable and manageable code, as changes to a superclass are inherited by all subclasses, reducing the need for changes across multiple classes.

Polymorphism is a cornerstone in the world of object-oriented programming, enabling more dynamic and flexible code. It allows objects to interact in a more abstract manner, focusing on the shared behavior rather than the specific types.

Understanding and effectively using polymorphism can lead to more robust and maintainable code, a crucial aspect for any software developer looking to excel in their field.

48. How Can You Avoid Memory Leaks in Java?

Avoiding memory leaks in Java, despite its automated garbage collection mechanism, requires a deep understanding of how memory allocation and release work in Java, alongside meticulous coding practices and effective use of analysis tools.

Let’s delve into some advanced and specific strategies for preventing memory leaks in Java applications:

Understand Object Lifecycle and Scope:

  • Scope Management : Ensure objects are scoped as narrowly as possible. For instance, use local variables within methods rather than class-level variables if the data does not need to persist beyond the method’s execution context.
  • Reference Management : Be cautious with static references. Static fields can keep objects alive for the lifetime of the class, potentially leading to memory leaks.

Efficient Use of Collections:

  • WeakHashMap : For cache implementations, consider using WeakHashMap . It uses weak references for keys, which allows keys (and their associated values) to be garbage-collected when no longer in use.
  • Data Structure Choice : Be mindful of the choice of data structure. For example, use ArrayList over LinkedList for large lists of data where frequent access is required, as LinkedList can consume more memory due to the storage of additional node references.

Leveraging WeakReferences and SoftReferences :

  • SoftReferences for Caches : Use SoftReference for memory-sensitive caches. The garbage collector will only remove soft-referenced objects if it needs memory, making them more persistent than weak references.
  • WeakReferences for Listeners : Utilize WeakReference for listener patterns where listeners might not be explicitly removed.

Managing Resources and I/O:

  • AutoCloseable and Try-with-Resources : For resources like streams, files, and connections, use try-with-resources for automatic closure. Ensure that objects implementing AutoCloseable are closed properly to release resources.

Inner Classes Handling:

  • Static Inner Classes : Prefer static inner classes over non-static to avoid the implicit reference to the outer class instance, which can prevent the outer instance from being garbage-collected.

Profiling and Leak Detection:

  • Heap Dump Analysis : Regularly analyze heap dumps in tools like Eclipse Memory Analyzer (MAT) to detect large objects and potential memory leaks.
  • Java Flight Recorder : Use Java Flight Recorder for runtime analysis and monitoring, which can help identify memory leaks.

ThreadLocal Variables Management:

  • Explicit Removal : Always remove ThreadLocal variables after use, particularly in thread-pooled environments like servlet containers or application servers.

ClassLoader Leaks:

  • ClassLoader Lifecycle : In environments with dynamic class loading/unloading (for example, web servers), ensure that class loaders are garbage collected when not needed. This involves ensuring that classes loaded by these class loaders are no longer referenced.

Garbage Collection Tuning:

  • GC Analysis : Analyze GC logs to understand the garbage collection behavior and identify potential memory leaks.
  • GC Algorithm Choice : Choose an appropriate garbage collection algorithm based on application needs, which can be tuned with JVM options for optimal performance.

String Interning:

  • Selective Interning : Be cautious with the String.intern() method. Unnecessary interning of strings can lead to a bloated String pool.

Static Analysis Tools:

Utilize tools like SonarQube, FindBugs, or PMD to statically analyze code for patterns that could lead to memory leaks.

Developer Training and Code Reviews:

Regularly train developers on best practices in memory management and conduct thorough code reviews with a focus on potential memory leak patterns.

Memory leak prevention in Java is a sophisticated practice that involves a thorough understanding of Java memory management, careful coding, diligent use of analysis tools, and regular monitoring.

By adopting these advanced practices, developers can significantly mitigate the risk of memory leaks, leading to more robust, efficient, and scalable Java applications.

49. Explain the Purpose of Java's Synchronized Block

The purpose of Java's synchronized block is to ensure thread safety in concurrent programming by controlling access to a shared resource among multiple threads.

In a multithreaded environment, where multiple threads operate on the same object, there's a risk of data inconsistency if the threads simultaneously modify the object. A synchronized block in Java is used to lock an object for exclusive access by a single thread.

Thread Safety and Data Consistency:

When different threads access and modify shared data, it can lead to unpredictable data states and inconsistencies. The synchronized block ensures that only one thread can execute a particular block of code at a time, thus maintaining data integrity.

Lock Mechanism:

In Java, each object has an intrinsic lock or monitor lock. When a thread enters a synchronized block, it acquires the lock on the specified object. Other threads attempting to enter the synchronized block on the same object are blocked until the thread inside the synchronized block exits, thereby releasing the lock.

Syntax and Usage:

The synchronized block is defined within a method, and you must specify the object that provides the lock:

The lockObject is a reference to the object whose lock the synchronized block acquires. It can be this to lock the current object, a class object for class-level locks, or any other object.

Advantages Over Synchronized Methods:

Compared to synchronized methods, synchronized blocks provide finer control over the scope and duration of the lock.

While a synchronized method locks the entire method, a synchronized block can lock only the part of the method that needs synchronization, potentially improving performance.

Avoiding Deadlocks:

Take care to avoid deadlocks, a situation where two or more threads are blocked forever, each waiting for the other's lock. This usually occurs when multiple synchronized blocks are locking objects in an inconsistent order.

Synchronized blocks also solve memory visibility problems. Changes made by one thread in a synchronized block are visible to other threads entering subsequent synchronized blocks on the same object.

Best Practices

  • Minimize Lock Contention : Keep the synchronized sections as short as possible to minimize lock contention and avoid performance bottlenecks.
  • Consistent Locking Order : Always acquire locks in a consistent order to prevent deadlocks.
  • Avoid Locking on Public Objects : Locking on public objects can lead to accidental and uncontrolled access to the lock, increasing the deadlock risk. Prefer private objects as lock targets.
  • Complement with Other Concurrency Tools : In some cases, using higher-level concurrency tools like ReentrantLock , Semaphore , or concurrent collections from java.util.concurrent package might be more appropriate.

Java's synchronized block is a critical tool for achieving thread safety in concurrent applications. Its proper use ensures data integrity and consistency by controlling access to shared resources. But, it requires careful consideration to avoid common pitfalls like deadlocks and performance issues due to excessive lock contention.

Understanding and applying these concepts is essential for developers working in a multithreaded environment to create robust and efficient Java applications.

50. Explain the Concept of Modules in Java

Modules in Java, introduced in Java 9 with the Java Platform Module System (JPMS), represent a fundamental shift in organizing Java applications and their dependencies.

Understanding modules is essential for modern Java development, as they offer improved encapsulation, reliable configuration, and scalable system architectures.

What are Java modules?

A module in Java is a self-contained unit of code and data, with well-defined interfaces for communicating with other modules. Each module explicitly declares its dependencies on other modules.

Modules enable better encapsulation by allowing a module to expose only those parts of its API which should be accessible to other modules, while keeping the rest of its codebase hidden. This reduces the risk of unintended usage of internal APIs.

Key Components of modules:

module-info.java : Each module must have a module-info.java file at its root, which declares the module's name, its required dependencies, and the packages it exports.

  • Here, com.example.myapp is the module name, java.sql is a required module, and com.example.myapp.api is the exported package.
  • Exports and Requires: The exports keyword specifies which packages are accessible to other modules, while requires lists the modules on which the current module depends.
  • Improved Application Structure: Modules encourage a cleaner, more organized code structure, helping in maintaining large codebases and improving code quality.
  • Reduced Memory Footprint: By only loading the required modules, applications can reduce their memory footprint and start-up time, enhancing performance.
  • Enhanced Security and Maintenance: Modules reduce the surface area for potential security vulnerabilities. They also simplify dependency management, making it easier to update and maintain libraries without affecting the entire system.

Consider a scenario where you are developing a large-scale application with various functionalities like user management, data processing, and reporting. By organizing these functionalities into separate modules (like usermodule , dataprocessmodule , reportmodule ), you can maintain them independently, avoiding the complexities of a monolithic application structure.

Modules in Java are a powerful feature for building scalable, maintainable, and efficient applications. They offer clear boundaries and contracts between different parts of a system, facilitating better design and architecture.

For developers and teams aiming to build robust Java applications, understanding and leveraging modules is not just a technical skill but a strategic approach to software development.

This modular architecture aligns with modern development practices, enabling Java applications to be more scalable and easier to manage in the long term.

image-34

As we wrap up this roundup of Java interview questions, I want to take a moment to thank the freeCodeCamp team. This platform is a fantastic resource for people learning to code, and it's great to have such a supportive community in the tech world.

I also want to thank the editorial team for their help in making this guide possible. Working together has been a great experience, and it's been rewarding to combine our efforts to help others learn Java.

It's important to reflect on the journey we've undertaken together. Java's robustness in Object-Oriented Programming (OOP) is a critical asset for developers at all levels, especially those aspiring to join top-tier tech firms. This handbook has aimed to provide a clear pathway to mastering Java interviews, focusing on the insights and techniques that matter most in the competitive landscape of big tech.

From the fundamentals to the more complex aspects of Java, I've sought to bridge the gap between basic Java knowledge and the sophisticated expertise that industry leaders like Google value. This resource is crafted not just for those new to Java, but also for those revisiting key concepts, offering a comprehensive understanding of the language in a practical context.

As you continue to explore the depths of Java, remember that mastering this language is not just about enhancing coding skills, but also about expanding your professional horizons. Java's significant role in IoT and its presence in billions of devices worldwide make it a language that can truly shape your career.

In closing, I hope this handbook has provided you with valuable insights and a strong foundation for your future endeavors in Java programming and beyond. Whether you're preparing for a big tech interview or simply looking to refine your software development skills, this guide is a stepping stone towards achieving those goals.

If you're keen on furthering your Java knowledge, here's a guide to help you conquer Java and launch your coding career . It's perfect for those interested in AI and machine learning, focusing on effective use of data structures in coding. This comprehensive program covers essential data structures, algorithms, and includes mentorship and career support.

Additionally, for more practice in data structures, you can explore these resources:

  • Java Data Structures Mastery - Ace the Coding Interview : A free eBook to advance your Java skills, focusing on data structures for enhancing interview and professional skills.
  • Foundations of Java Data Structures - Your Coding Catalyst : Another free eBook, diving into Java essentials, object-oriented programming, and AI applications.

Visit LunarTech's website for these resources and more information on the bootcamp .

Connect with Me:

  • Follow me on LinkedIn for a ton of Free Resources in CS, ML and AI
  • Visit my Personal Website
  • Subscribe to my The Data Science and AI Newsletter

About the Author

I'm Vahe Aslanyan, deeply engaged in the intersecting worlds of computer science, data science, and AI. I invite you to explore my portfolio at vaheaslanyan.com, where I showcase my journey in these fields. My work focuses on blending full-stack development with AI product optimization, all fueled by a passion for innovative problem-solving.

6539302e3cd34bb5cbabe5f9_Vahe%20Aslanyan%20(256%20x%20256%20px)

I've had the privilege of contributing to the launch of a well-regarded data science bootcamp and collaborating with some of the best minds in the industry. My goal has always been to raise the bar in tech education, making it accessible and standard for everyone.

As we conclude our journey here, I want to thank you for your time and engagement. Sharing my professional and academic experiences in this book has been a rewarding experience. I appreciate your involvement and look forward to seeing how it helps you advance in the tech world.

I'm Vahe Aslanyan, dedicated to making AI and data science education inclusive and accessible. I guide developers towards clear tech understanding in software engineering.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

  • C Program : Remove Vowels from A String | 2 Ways
  • C Program : Remove All Characters in String Except Alphabets
  • C Program : Sorting a String in Alphabetical Order – 2 Ways
  • C Program To Check If Vowel Or Consonant | 4 Simple Ways
  • C Program To Check Whether A Number Is Even Or Odd | C Programs
  • C Program To Count The Total Number Of Notes In A Amount | C Programs
  • C Program To Print Number Of Days In A Month | Java Tutoring
  • C Program To Input Any Alphabet And Check Whether It Is Vowel Or Consonant
  • C Program To Find Reverse Of An Array – C Programs
  • C Program To Check A Number Is Negative, Positive Or Zero | C Programs
  • C Program To Find Maximum Between Three Numbers | C Programs
  • C Program Inverted Pyramid Star Pattern | 4 Ways – C Programs
  • C Program To Check If Alphabet, Digit or Special Character | C Programs
  • C Program To Check Whether A Character Is Alphabet or Not
  • C Program To Check Character Is Uppercase or Lowercase | C Programs
  • C Program To Check Whether A Year Is Leap Year Or Not | C Programs
  • C Program To Calculate Profit or Loss In 2 Ways | C Programs
  • C Program Area Of Triangle | C Programs
  • C Program To Check If Triangle Is Valid Or Not | C Programs
  • C Program Find Circumference Of A Circle | 3 Ways
  • C Program Area Of Rectangle | C Programs
  • X Star Pattern C Program 3 Simple Ways | C Star Patterns
  • C Program Area Of Rhombus – 4 Ways | C Programs
  • C Program To Check Number Is Divisible By 5 and 11 or Not | C Programs
  • C Program Hollow Diamond Star Pattern | C Programs
  • Mirrored Rhombus Star Pattern Program In c | Patterns
  • C Program Area Of Isosceles Triangle | C Programs
  • C Program To Find Area Of Semi Circle | C Programs
  • C Program Area Of Parallelogram | C Programs
  • C Program Area Of Trapezium – 3 Ways | C Programs
  • C Program Area Of Square | C Programs
  • C Program Check A Character Is Upper Case Or Lower Case
  • C Program To Find Volume of Sphere | C Programs
  • C Program to find the Area Of a Circle
  • C Program Area Of Equilateral Triangle | C Programs
  • Hollow Rhombus Star Pattern Program In C | Patterns
  • C Program To Count Total Number Of Notes in Given Amount
  • C Program To Calculate Volume Of Cube | C Programs
  • C Program To Find Volume Of Cone | C Programs
  • C Program To Calculate Perimeter Of Rectangle | C Programs
  • C Program To Calculate Perimeter Of Rhombus | C Programs
  • C Program Volume Of Cuboid | C Programs
  • C Program To Calculate Perimeter Of Square | C Programs
  • C Program Count Number Of Words In A String | 4 Ways
  • C Program To Search All Occurrences Of A Character In String | C Programs
  • C Program To Copy All Elements From An Array | C Programs
  • C Program To Left Rotate An Array | C Programs
  • C Program To Delete Duplicate Elements From An Array | 4 Ways
  • C Program Volume Of Cylinder | C Programs
  • C Program To Compare Two Strings – 3 Easy Ways | C Programs
  • C Mirrored Right Triangle Star Pattern Program – Pattern Programs
  • C Program To Toggle Case Of Character Of A String | C Programs
  • C Program To Count Occurrences Of A Word In A Given String | C Programs
  • C Square Star Pattern Program – C Pattern Programs | C Programs
  • C Program To Remove First Occurrence Of A Character From String
  • C Program To Search All Occurrences Of A Word In String | C Programs
  • C Program Inverted Right Triangle Star Pattern – Pattern Programs
  • C Programs – 500+ Simple & Basic Programming Examples & Outputs
  • C Program To Reverse Words In A String | C Programs
  • C Program To Delete An Element From An Array At Specified Position | C Programs
  • Hollow Square Pattern Program in C | C Programs
  • C Program To Find Reverse Of A string | 4 Ways
  • C Program To Remove Last Occurrence Of A Character From String
  • C Program To Remove Repeated Characters From String | 4 Ways
  • C Plus Star Pattern Program – Pattern Programs | C
  • Rhombus Star Pattern Program In C | 4 Multiple Ways
  • C Program To Check A String Is Palindrome Or Not | C Programs
  • C Program Replace First Occurrence Of A Character With Another String
  • C Pyramid Star Pattern Program – Pattern Programs | C
  • C Program To Sort Even And Odd Elements Of Array | C Programs
  • C Program To Search An Element In An Array | C Programs
  • C Program To Remove Blank Spaces From String | C Programs
  • C Program To Trim Leading & Trailing White Space Characters From String
  • C Program Number Of Alphabets, Digits & Special Character In String | Programs
  • C Program Replace All Occurrences Of A Character With Another In String
  • C Program To Copy One String To Another String | 4 Simple Ways
  • C Program To Find Maximum & Minimum Element In Array | C Prorams
  • C Program To Find Last Occurrence Of A Word In A String | C Programs
  • Merge Two Arrays To Third Array C Program | 4 Ways
  • C Program Right Triangle Star Pattern | Pattern Programs
  • C Program To Count Frequency Of Each Character In String | C Programs
  • C Program To Find Last Occurrence Of A Character In A Given String
  • C Program To Find First Occurrence Of A Word In String | C Programs
  • C Program To Concatenate Two Strings | 4 Simple Ways
  • C Program Find Maximum Between Two Numbers | C Programs
  • C Program To Trim White Space Characters From String | C Programs
  • C Program Count Number Of Vowels & Consonants In A String | 4 Ways
  • C Program To Sort Array Elements In Ascending Order | 4 Ways
  • Highest Frequency Character In A String C Program | 4 Ways
  • C Program To Count Number Of Even & Odd Elements In Array | C Programs
  • C Program To Count Frequency Of Each Element In Array | C Programs
  • C Program To Remove First Occurrence Of A Word From String | 4 Ways
  • C Program To Count Occurrences Of A Character In String | C Programs
  • C Program To Trim Trailing White Space Characters From String | C Programs
  • C Program To Put Even And Odd Elements Of Array Into Two Separate Arrays
  • C Program To Print All Unique Elements In The Array | C Programs
  • C Program To Convert Lowercase String To Uppercase | 4 Ways
  • C Program To Print Number Of Days In A Month | 5 Ways
  • Diamond Star Pattern C Program – 4 Ways | C Patterns
  • C Program To Insert Element In An Array At Specified Position
  • C Program To Convert Uppercase String To Lowercase | 4 Ways
  • C Program Hollow Inverted Right Triangle Star Pattern
  • C Program To Count Number Of Negative Elements In Array
  • C Program To Find Sum Of All Array Elements | 4 Simple Ways
  • C Program To Sort Array Elements In Descending Order | 3 Ways
  • C Program Count Number of Duplicate Elements in An Array | C Programs
  • C Program To Remove All Occurrences Of A Character From String | C Programs
  • C Program Hollow Inverted Mirrored Right Triangle
  • C Program To Input Week Number And Print Week Day | 2 Ways
  • C Program To Read & Print Elements Of Array | C Programs
  • C Program To Right Rotate An Array | 4 Ways
  • C Program To Replace Last Occurrence Of A Character In String | C Programs
  • C Program Hollow Mirrored Rhombus Star Pattern | C Programs
  • 8 Star Pattern – C Program | 4 Multiple Ways
  • C Program To Find Lowest Frequency Character In A String | C Programs
  • C Program Half Diamond Star Pattern | C Pattern Programs
  • C Program To Find First Occurrence Of A Character In A String
  • C Program To Find Length Of A String | 4 Simple Ways
  • C Program Hollow Mirrored Right Triangle Star Pattern
  • Hollow Inverted Pyramid Star Pattern Program in C
  • Right Arrow Star Pattern Program In C | 4 Ways
  • C Program To Print All Negative Elements In An Array
  • C Program Hollow Right Triangle Star Pattern
  • C Program : Check if Two Strings Are Anagram or Not
  • C Program : Capitalize First & Last Letter of A String | C Programs
  • C Program : Check if Two Arrays Are the Same or Not | C Programs
  • Left Arrow Star Pattern Program in C | C Programs
  • C Program Inverted Mirrored Right Triangle Star Pattern
  • C Program Mirrored Half Diamond Star Pattern | C Patterns
  • Hollow Pyramid Star Pattern Program in C
  • C Program : Non – Repeating Characters in A String | C Programs
  • C Program : Sum of Positive Square Elements in An Array | C Programs
  • C Program : To Reverse the Elements of An Array | C Programs
  • C Program : Find Longest Palindrome in An Array | C Programs
  • C Program Lower Triangular Matrix or Not | C Programs
  • C Program : Maximum Scalar Product of Two Vectors
  • C Program Merge Two Sorted Arrays – 3 Ways | C Programs
  • C Program : Check If Arrays are Disjoint or Not | C Programs
  • C Program : Convert An Array Into a Zig-Zag Fashion
  • C Program : Minimum Scalar Product of Two Vectors | C Programs
  • C program : Find Median of Two Sorted Arrays | C Programs
  • C Program : Find Missing Elements of a Range – 2 Ways | C Programs
  • C Program Transpose of a Matrix 2 Ways | C Programs
  • C Program Patterns of 0(1+)0 in The Given String | C Programs
  • C Program : To Find Maximum Element in A Row | C Programs
  • C Program : Rotate the Matrix by K Times | C Porgrams
  • C Program To Check Upper Triangular Matrix or Not | C Programs
  • C Program : Non-Repeating Elements of An Array | C Programs
  • C Program : To Find the Maximum Element in a Column
  • C Program : Check if An Array Is a Subset of Another Array
  • C Program : Rotate a Given Matrix by 90 Degrees Anticlockwise
  • C Program Sum of Each Row and Column of A Matrix | C Programs

Learn Java Java Tutoring is a resource blog on java focused mostly on beginners to learn Java in the simplest way without much effort you can access unlimited programs, interview questions, examples

Exception handling in java – tutorial & examples.

in Java Tutorials April 19, 2024 Comments Off on Exception Handling In Java – Tutorial & Examples

What is Exception Handling In Java – When we work with a program we come up with different kinds of errors like syntactical errors, logical errors, runtime errors, etc. let us try to differentiate these errors with a simple program.

Example Program To Differentiate the Errors:

The above program will not cross the compilation stage because there is a semi-colon missing when declaring the variables a and b.

  • This is an error as per the syntax of Java language.
  • When our code fails to comply with the syntax of the language, the compiler will generate an error.
  • These kinds of errors are known as syntactical errors or compilation errors.
  • As the compiler catches the error and its location, we should make the required modifications and recompile the updated program.

Generally, these kinds of errors come to the people who do not have enough grip on the syntax of the language.

Then we have printed “sum is “+c with the first println() statement. We are trying to print the sum but in the previous statement, we have used multiplication symbol instead of the addition symbol.

These kinds of errors cannot be caught by the compiler. So the user will see some wrong result. This problem arose due to the wrong way of writing the logic. So these are known as logical errors.

For simplicity and easy understanding, we have given such a simple example (addition and multiplication). But in real time, a complex problem may be understood by the programmer in a wrong way and as per the understanding, the programmer will write the code.

At the testing stage, the mistake will be caught and as per the testing report, the programmer will have to make the required modifications to the program. Generally, this kind of problem occurs when we don’t have enough grip on the problem domain.

The third error we have seen in the above example is printing the quotient after the division. If the division is done with normal values, then we would get a normal result. But in our example, we are dividing a value (45) with 0.

In the subject of mathematics, there is no proper value defined for a division with 0 (it is said as infinite). So in Java also this operation cannot be performed.

Simple Flow Chart For Java Exception Handling

Java exception handling

As there is a limitation in the concept of mathematics, the same is reflected in Java, and the Java runtime system cannot proceed from that point. Hence it terminates the program (actually, the current thread) by printing some messages corresponding to the error.

  • These kinds of errors are known as runtime errors. But in a real-time environment, a program should not be terminated at any cost. It will be embarrassing to the user.
  • Not only that but also we (programmer) should know what problems the client/user has got while working. When we come to know the problem, we can find a solution, update the program, and give it to the user.
  • If the program does not terminate even such an error occur, that will be great. So programmer should have a provision not to terminate the program and handle that situation.

While handling, we can skip that part (which created the runtime error) and continue with the rest of the program.

Java provides a special mechanism to deal with these runtime errors. In Java parlance, the ‘runtime errors’ are known as ‘exceptions’. Handling (solving) the exception (errors) is known as ‘Exception Handling’.

For that it provides the keywords try, catch, throw, throws and finally.

Java Exception Handling

Let us see an example here that may raise an exception (runtime error) . When the program is executed the program will be terminated abnormally.

As the program is trying to divide a value (4) by 0, an exception is raised and the program will be terminated. In the given program, there are 3 statements. The first statement will be executed normally and prints “Computer”.

The second statement will raise an exception and terminates the program. So the control will not come to the third statement.

Suppose, we want to see that the program will not be terminated at the second statement, but skips the problem creating a statement, and executes the third statement also.

For that, we can put the problem creating a statement in a try block. Generally, the statements that may raise an exception are placed in the ‘try’ block. If an exception is raised the control goes to the ‘catch’ block.

If no exception is raised, then the catch block is skipped. So if we write the above program in the following way, then the program will not be terminated abnormally.

In the above program, first “Computer” is printed normally. Then an exception is raised in the try block and control comes to the catch block. As there is no statement in the catch block, nothing will happen there. But the control comes out of the catch block and prints “Programming”.

If we don’t want to take any specific action when an exception is raised, then we can keep the catch block empty. If we want to perform any action (some alternative for the code in try block), then we can write some code in the catch block.

The Actual Work – Exception Handling

When a runtime error occurs, the system creates an object corresponding to the error and stores the information about the error in that object.

For example, when an attempt is made to divide by 0 an object of the class ArithmeticException is raised.

Similarly, when an attempt is made to access an element outside the array bounds (limits) then an object of the class ArrayIndexOutOfBoundsException is raised.

Suppose, when we try to access a character out of a String (using method like charAt()) then an object of the class StringIndexOutOfBoundsException is raised.

Once such an object is raised, the system throws that object to the catch block. If there is no catch block to receive the object, then the program will be terminated abnormally.

Otherwise, the object will be received by the catch block and the code we have specified there will be executed. That is why we have used an Exception reference at catch block (this is similar to a formal argument in a method).

The exception is a parent class for almost all the exceptions in Java. So the parent class reference will receive the HashCode of the created (and thrown) object. If we want to get information about the created object (and the error details) we can use that formal-argument-like variable.

Multiple Catch Blocks

The try block may raise different types of exceptions and we may want to take a different action for each of them. In that case, we can have multiple catch blocks associated with a try block.

Whatever the number of catch blocks we have for a try block, we should see a parent class catch block does not come before its child class catch block.

Otherwise, the parent class catch block handles the child class exception and the child class catch block becomes unreachable. The ‘unreachable’ code is not allowed in Java and such a situation will give a compilation error.

If we want to perform any activity irrespective of the exception raised ( it means the action will be performed whether an exception is raised or not) then we can put such code in the finally block. The finally block is a place just after the catch block.

By default, the system throws an exception object when something goes wrong. It means the system has to create an object and throw (pass) it to catch block.

There may be some situations where it is acceptable to the system but not acceptable to the requirements of our program/project. In that case, we can create and throw the exception objects.

Creating an exception object is similar to the way we create any other object. To throw the created object, we use the keyword ‘throw’. This can be seen in the following example.

There are two types of exceptions

  • Checked exceptions
  • Unchecked exceptions

Checked Exceptions:

When there is a possibility for a checked exception to rising, the compiler will raise an error at compilation stage. So it is our responsibility to handle the checked exceptions without fail.

On the other hand, the compiler does not raise an error if there is a possibility for an unchecked exception. In fact, the compiler won’t check for them. This is why those exceptions are known as unchecked exceptions.

The exceptions for which the compiler would check are known as checked exceptions.

For all the exception classes, Throwable is the base class. The Throwable, Exception, all child classes of Exception except RuntimeException have checked exception classes.

The RuntimeException and all its child classes are unchecked exceptions. Similarly, Error and all its child classes are also unchecked only.

If there is any possibility for a checked exception to rising and we want the exception to be handled by another method that has called this method, then we should notify to the system that the exception is not being handled here so the caller should handle this.

If we notify so, then the compiler will not raise the error. To notify this, we use the clause ‘throws’. The ‘throws’ clause puts the responsibility of handling on the calling method.

If the calling method does not provide the exception handling, then the compiler raises an error at the calling method. In the following example, we can see the usage of ‘throws’.

In the above example, if we omit the ‘throws Exception’ at the fun() header then a compilation error will be raised. As Exception is a checked exception, throws clause is required.

In the above example, if we throw an unchecked exception (like ArithmeticException, NumberFormatException , etc) then we need not use the throws clause. The system can automatically throw the exception to the calling method.

If we want we can create our own exceptions also. Every exception class that we create (on our own) should be part of the exception hierarchy that starts at Throwable.

So we should make our class a child class to any of the existing exception classes.

Related Posts !

assignment questions on exception handling in java

VPN Blocked by Java Security on PC? Here’s How to Fix That

May 25, 2024

How to Read All Elements In Vector By Using Iterator

April 21, 2024

Remove An Element From Collection Using Iterator Object In Java

assignment questions on exception handling in java

30+ Number & Star Pattern Programs In Java – Patterns

Java thread by extending thread class – java tutorials, copying character array to string in java – tutorial, java if else – tutorial with examples | learn java.

If else Java – statement complete tutorial. Here we cover in-depth information with examples on ...

Javatpoint Logo

Exception Handling

JavaTpoint

Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:

hierarchy of exception handling

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception. However, according to Oracle, there are three types of exceptions namely:

  • Checked Exception
  • Unchecked Exception

hierarchy of exception handling

Difference between Checked and Unchecked Exceptions

1) checked exception.

The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Exception Keywords

Java provides five keywords that are used to handle the exception. The following table describes each.

Java Exception Handling Example

Let's see an example of Java Exception Handling in which we are using a try-catch statement to handle the exception.

JavaExceptionExample.java

In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.

Common Scenarios of Java Exceptions

There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

2) A scenario where NullPointerException occurs

If we have a null value in any variable , performing any operation on the variable throws a NullPointerException.

3) A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may result into NumberFormatException. Suppose we have a string variable that has characters; converting this variable into digit will cause NumberFormatException.

4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.

Java Exceptions Index

  • Java Try-Catch Block
  • Java Multiple Catch Block
  • Java Nested Try
  • Java Finally Block
  • Java Throw Keyword
  • Java Exception Propagation
  • Java Throws Keyword
  • Java Throw vs Throws
  • Java Final vs Finally vs Finalize
  • Java Exception Handling with Method Overriding
  • Java Custom Exceptions

Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

Download Interview guide PDF

Exception handling interview questions, download pdf, introduction.

An Exception refers to abnormal behaviour of an application that occurs at the time of execution that could lead to the termination of that application if not handled. Exceptions could include sudden network errors, database connection errors, errors due to non-existent or corrupt files, logical errors that were not handled by the developers and many more. Java provides a great way of handling Exceptions that results in a robust application that does not fail in case of abnormalities. Due to its importance, exception handling has become a very important and favourite topic amongst interviewers. Every software developer should know how to handle unexpected errors while developing an application.

In this article, we will go through the commonly asked Exception-Handling Interview Questions for both freshers and experienced software developers:

Exception Handling Interview Questions for Freshers

Exception handling interview questions for experienced, mcq questions on exception handling in java, 1. what is an exception in java.

An exception is an abnormal event that disrupts the flow of normal program execution that unless handled could lead to the termination of that program. In real-world scenarios, a program could run into an exception if it tries to access a corrupted/non-existent file or if a network error happens or if the JVM runs out of memory, or if the code is trying to access an index of an array which does not exist and so on.

2. What is exception handling in Java and what are the advantages of exception handling?

Exception Handling is the technique of handling unexpected failures that could occur in a program so that the program does not terminate and normal execution flow is maintained. Consider an example program where we have 6 statement blocks as shown in the below image. Statements 1 and 2 execute successfully. While executing the statement 3 block, an unexpected error occurred. Now the Java program checks if there is any exception-handling mechanism present. If an exception handling block is present, then the exception is handled gracefully and the program continues with the execution of the statement 4 block. If not, the program gets terminated.

assignment questions on exception handling in java

The following are some of the A dvantages of using Exception Handling in Java :

  • The most important advantage of having an exception-handling technique is that it avoids abnormal program termination and the normal flow of the program is maintained.
  • Provides flexibility to the programmers to define/handle what should occur in cases of failures/errors thereby making the applications more robust and immune to unexpected scenarios.
  • Provides stable user experience in cases of failures by providing means to let the user know what made the program fail.

3. How are exceptions handled in Java?

In Java, exceptions could be handled in the following ways:

  • try-catch block: The try section holds the code that needs to be normally executed and it monitors for any possible exception that could occur. The catch block “catches” the exception thrown by the try block. It could consist of logic to handle failure scenario or the catch block could simply rethrow the exception by using the “throw” keyword.
  • finally block: Regardless of whether an exception has occurred or not, if we need to execute any logic, then we place it in the final block that is usually associated with the try-catch block or just with the try block. The final block is not executed when System.exit(0) is present in either the try or catch block.

Consider an example where we need to get the value of the score from a file called “resultFile”. When we access the file, the file could exist and we get the score and everything happens normally. But there could be cases where the file was accidentally deleted. In this case, when the program tries to access that file, then it throws FileNotFoundException . There are 2 ways to handle this exception (Depending on the requirements, we need to choose what way is the most appropriate for us):-

  • Case 1: Throw IllegalArgumentException stating the file does not exist as shown in the logic below.
  • Case 2: Return the score as 0 and log the error that file doesn’t exist as shown in the logic below.

Finally, irrespective of whether the code running normally or not, we would want to close the resources. This could run in the finally block as shown below:

Note: As of Java 7, the new feature “try-with-resources” helps to autoclose the resources that extend the “AutoCloseable” interface. The close() method will be called when it exits the try-with-resources block. For example, the above code which has a close() method call could be simplified as shown below:
  • Sometimes, the program could throw more than 1 exception. In this case, Java supports the usage of multiple catch blocks. Our example could also encounter a NumberFormatException exception while parsing integer numbers and this could be handled as shown below:
  • Multiple catch blocks are useful if we have different exception-handling logic for different types of exceptions. If our logic of handling the exception is the same (as in the above scenario), then Java7 introduced the feature to union the catch blocks - handle multiple exceptions in the same catch block. The above could now be simplified to:

4. What is exception propagation in Java?

Exception propagation is a process where the compiler makes sure that the exception is handled if it is not handled where it occurs. If an exception is not caught where it occurred, then the exception goes down the call stack of the preceding method and if it is still not caught there, the exception propagates further down to the previous method. If the exception is not handled anywhere in between, the process continues until the exception reaches the bottom of the call stack. If the exception is still not handled in the last method, i.e, the main method, then the program gets terminated. Consider an example -

We have a Java program that has a main() method that calls method1() and this method, in turn, calls another method2(). If an exception occurs in method2() and is not handled, then it is propagated to method1(). If method1() has an exception handling mechanism, then the propagation of exception stops and the exception gets handled. The same has been represented in the image below:

assignment questions on exception handling in java

5. What are the important methods defined in Java’s Exception Class?

The throwable class is the base class of Exception. Exception and its subclasses do not provide specific methods. All the methods that could be used by Exception are defined in the Throwable class. Some of the most important methods are as follows:

  • String getMessage(): This method returns the Throwable message of type String. The message could be given at the time of creating an exception by using the constructor.
  • String getLocalizedMessage(): This method can be overridden by the Exception and its subclasses to give locale-specific messages to the calling program. The implementation of this method in the Throwable class by default uses the getMessage() that returns the exception message. Hence, to use this method, it should be overridden to avoid this default behaviour.
  • synchronized Throwable getCause(): This returns the exception cause if it is known. If the cause is not known, it returns null. The cause is returned if it was provided via the constructors requiring Throwable or if it was set after the creation of exception by using the initCause(Throwable) method. Exception and its subclasses may override this method to return a cause set by different means.
  • String toString(): This returns the Throwable information in String format consisting of the Throwable class name and localized message.
  • void printStackTrace(): As the name indicates, this prints the stack trace data to the standard error stream. By default, it prints on the console. But, there are overloaded versions of this method where we can pass either PrintWriter or PrintStream as an argument to write stack trace data to a specific file or stream.

Learn via our Video Courses

6. what are runtime exceptions in java.

Runtime exceptions are those exceptions that occur at the run time of the program execution. These exceptions are not noticed by the compiler at the compile time and hence the program successfully gets compiled. Therefore, they are also called unchecked exceptions. All subclasses of the java.lang.RunTimeException class and java.lang.Error class belongs to runtime exceptions. Examples of runtime exceptions include NullPointerException, NumberFormatException, ArrayIndexOutOfBoundException, StackOverflowError, ClassCastException, ArithmeticException, ConcurrentModificationException, etc.

7. What is the difference between the throw and throws keywords in Java?

The throw keyword allows a programmer to throw an exception object to interrupt normal program flow. The exception object is handed over to the runtime to handle it. For example, if we want to signify the status of a task is outdated, we can create an OutdatedTaskException that extends the Exception class and we can throw this exception object as shown below:

The throws keyword in Java is used along with the method signature to specify exceptions that the method could throw during execution. For example, a method could throw NullPointerException or FileNotFoundException and we can specify that in the method signature as shown below:

8. How do you handle checked exceptions?

Checked Exceptions can be handled by either using a try-catch block or by using the throws clause in the method declaration. If these exceptions are not handled properly, then the program would fail to compile.

9. Differentiate between Checked Exception and Unchecked Exceptions in Java.

The followings programs are the differences between Checked and Unchecked Exceptions:

10. Can you catch and handle Multiple Exceptions in Java?

There are three ways to handle multiple exceptions in Java:

  • Since Exception is the base class for all exception types, make use of a catch block that catches the Exception class-

However, it is recommended to use accurate Exception handlers instead of generic ones. This is because having broad exception handlers could make the code error-prone by catching exceptions that were not anticipated in the software design and could result in unexpected behavior.

  • From Java 7 onwards, it is now possible to implement multiple catch blocks as shown below -

When we are using multiple catch blocks, we need to ensure that in a case where the exceptions have an inheritance relationship, the child exception type should be the first and the parent type later to avoid a compilation error.

  • Java 7 also began to provide the usage of multi-catch blocks for reducing duplication of code if the exception handling logic was similar for different exception types. The syntax of the multi-catch block is as shown below-

11. What is a stack trace and how is it related to an Exception?

A stack trace is information consisting of names of classes and methods that were invoked right from the start of program execution to the point where an exception occurred. This is useful to debug where exactly the exception occurred and due to what reasons. Consider an example stack trace in Java,

To determine where an exception has occurred, we need to check for the beginning of the trace that has a list of “at …”. In the given example, the exception has occurred at Line Number 26 of the Book.java class in the getBookTitle() method. We can look at this stack trace and go to the method and the line number mentioned in the trace and debug for what could have caused the NullPointerException. Furthermore, we can get to know that the getBookTitle() method in the Book.java class was called by the getBookTitlesOfAuthor() method in the Author.java class in Line Number 15 of the file and this in turn was called by the main() method of the DemoClass.java file in Line Number 14.

12. What is Exception Chaining?

Exception Chaining happens when one exception is thrown due to another exception. This helps developers to identify under what situation an Exception was thrown that in turn caused another Exception in the program. For example, we have a method that reads two numbers and then divides them. The method throws ArithmeticException when we divide a number by zero. While retrieving the denominator number from the array, there might have been an IOException that prompted to return of the number as 0 that resulted in ArithmeticException . The original root cause in this scenario was the IOException . The method caller would not know this case and they assume the exception was due to dividing a number by 0. Chained Exceptions are very useful in such cases. This was introduced in JDK 1.4.

13. Can we have statements between try, catch and finally blocks?

No. This is because they form a single unit.

14. How are the keywords final, finally and finalize different from each other?

  • we can declare a variable as final (meaning, variable value cannot be changed).
  • we can declare a method as final (meaning, that method cannot be overridden).
  • we can declare a class as final (meaning, that class cannot be extended).
  • finally keyword: This is used in conjunction with the try-catch block or the try block where we want to run some logic whether or not an exception has occurred.
  • finalize keyword: This is a method called by the Garbage Collector just before destroying the objects no longer needed in the program.

15. What is the output of this below program?

When the expression is evaluated, the denominator becomes zero. Hence Java would throw ArithmeticException when it’s executed. The exception logs would be:

16. What is the difference between ClassNotFoundException and NoClassDefFoundError?

Both these exceptions occur when ClassLoader or JVM is not able to find classes while loading during run-time. However, the difference between these 2 are:

  • ClassNotFoundException: This exception occurs when we try to load a class that is not found in the classpath at runtime by making use of the loadClass() or Class.forName() methods.
  • NoClassDefFoundError: This exception occurs when a class was present at compile-time but was not found at runtime.

17. What do you understand by an unreachable catch block error?

This error is thrown by the compiler when we have multiple catch blocks and keep parent classes first and subclasses later. The catch blocks should follow the order of the most specific ones at the top to the most general ones at the bottom. If this is not followed, an unreachable catch block error is thrown during compile time.

1. Explain Java Exception Hierarchy.

Exceptions in Java are hierarchical and follow inheritance to categorize different kinds of exceptions. The parent class of all exceptions and errors is Throwable. This class has 2 child classes - Error and Exception.

  • Errors are those abnormal failures that are not in the scope of recovery for the application. It is not possible to anticipate errors or recover from them. Errors could be due to failures in hardware, out-of-memory, JVM crash, etc.
  • Checked Exceptions are those that can be anticipated in the program at the time of compilation and we should try to handle this otherwise it leads to a compilation error. IllegalAccessException, ClassNotFoundException, and FileNotFoundException are some of the types of checked exceptions. Exception is the parent class of all checked exceptions.
  • Unchecked exceptions are those exceptions that occur during runtime and are not possible to identify at the time of compilation. These exceptions are caused due to mistakes in application programming - for example, we try to access an element from an array index that is out of bounds from the length of the array, while trying to run operations on null objects and so on. RuntimeException, ArrayIndexOutOfBoundException, NullPointerException, ClassCastException, NumberFormatException, IllegalArgumentException, etc are some of the types of unchecked exceptions. The parent class of all runtime/unchecked exceptions is RuntimeException.

The exception hierarchy in Java has been depicted in the image below:

assignment questions on exception handling in java

2. What does JVM do when an exception occurs in a program?

When there is an exception inside a method, the method creates and passes (throws) the Exception object to the JVM. This exception object has information regarding the type of exception and the program state when this error happens. JVM is then responsible for finding if there are any suitable exception handlers to handle this exception by going backwards in the call stack until it finds the right handler. If a matching exception handler is not found anywhere in the call stack, then the JVM terminates the program abruptly and displays the stack trace of the exception.

3. What happens when an exception is thrown by the main method?

When there is an exception thrown by the main() method if the exception is not handled, then the program is terminated by the Java Runtime, and the exception message along with the stack trace is printed in the system console.

4. Is it possible to throw checked exceptions from a static block?

We cannot throw a check exception from a static block. However, we can have try-catch logic that handles the exception within the scope of that static block without rethrowing the exception using the throw keyword. The exceptions cannot be propagated from static blocks because static blocks are invoked at the compiled time only once and no method invokes these blocks.

5. What happens to the exception object after exception handling is complete?

The exception object will be garbage collected.

6. What are different scenarios where “Exception in thread main” types of error could occur?

The following are some of the scenarios causing an exception in the main thread:

  • Exception in thread main java.lang.UnsupportedClassVersionError: This occurs when the Java class is compiled from one JDK version and we run the class in another JDK version.
  • Exception in thread main java.lang.NoSuchMethodError: main: This occurs when we try to run a class that has no main method.
  • Exception in thread main java.lang.NoClassDefFoundError: This occurs if a ClassLoader is unable to find that class in the classpath at the time of loading it.
  • Exception in thread “main” java.lang.ArithmeticException: This is an example exception. Here, in the logic, ArithmeticException was thrown from the main method due to some erroneous logic in the main or due to the methods called from the main that threw this exception but was not handled there.

7. Under what circumstances should we subclass an Exception?

When there are exceptions that are to be thrown by the application, but the type is not represented by any of the existing Exception types in Java, then we can provide more detailed information by creating a custom exception. The creation of custom exceptions depends on the business logic. While creating a custom exception, it is recommended to inherit from the most specific Exception class that relates to the exception we want to throw. If there are no such classes available, then we can choose the Exception class as the parent for this new custom exception. Consider an example - We want to access a file and return the first line of the file content.

In the above case, when there is an exception while reading the file - we do not know if it was caused due to absence of the file or if the name of the file provided was wrong. To narrow this down, we will create a custom exception called InvalidFileNameException by extending the Exception class as shown below:

To create a custom exception, we should also provide a constructor that makes a call to the parent class constructor by using the super keyword. Our custom exception is ready. The code logic now becomes:

8. What happens when you run the below program?

We know that the FileNotFoundException is the subclass of IOException - By the rule of multiple catch block, we need to have the most specific exception at the top and the most generic exception at the bottom. If there are no parent-child relationships between the exceptions, they can be placed anywhere. In this example, JAXBException is not related to IOException and FileNotFoundException exceptions. Hence, it can be placed anywhere in the multiple catch block structure. However, IOException being the parent class is mentioned at the beginning and that is followed by FileNotFoundException. This results in an error - Unreachable catch block for FileNotFoundException. It is already handled by the catch block for IOException. To fix this issue, depending on the business requirements, we can either remove the FileNotFoundException from the throws list and catch block OR we can rearrange the catch blocks as shown below:

9. Does the finally block always get executed in the Java program?

The finally blocks are meant to be executed whenever there is an exception or not in the try-catch blocks. However, there is one scenario where this block does not get executed. It is when we use System.exit(0) in either try or catch block. This is because the System.exit(0) terminates the running JVM.

10. Why it is always recommended to keep the clean-up activities like closing the I/O resources or DB connections inside a finally block?

When there is no explicit logic to terminate the system by using System.exit(0) , finally block is always executed irrespective of whether the exception has occurred or not. By keeping these cleanup operations in the finally block, it is always ensured that the operations are executed and the resources are closed accordingly. However, to avoid exceptions in the finally block, we need to add a proper validation check for the existence of the resource and then attempt to clean up the resources accordingly.

11. Are we allowed to use only try blocks without a catch and finally blocks?

Before Java 7, we were not allowed to use only try blocks. The try block should have been followed by a catch or a finally block. But from Java 7 onwards, we can simply have a try block with a catch or finally blocks in the form of try-with-resources that takes parameters implementing the AutoCloseable interface. Note that, if the parameters do not implement the AutoCloseable interface, then it leads to an error.

12. What happens when the below program is run?

The program compiles successfully and it runs and displays nothing as no logic in both methods could result in an exception.

If there are any exceptions in the demoMethod() , we can always catch the exception and handle it. If the method foobar() declares NullPointerException using throws clause, the method doesn’t need to throw an exception. However, if there is a logic that results in performing operations on null objects inside the foobar() method, then NullPointerException will be thrown by the method to the main() method. Since there is no exception handling for this foobar() method, the program will terminate displaying the error message and stack trace.

13. Is it possible to throw an Exception inside a Lambda Expression’s body?

Yes, it is possible. However, we need to note two points:

  • If we are using a standard functional interface that is given by Java, then we can throw only unchecked exceptions. This is because the standard functional interfaces of Java do not have a “throws” clause defined in their signature. For example, we can throw IllegalArgumentException inside a function interface as shown below:
  • If we are using custom functional interfaces, then we can throw checked as well as unchecked exceptions. Custom functional interfaces can be defined by using the @FunctionalInterface keyword.

14. What are the rules we should follow when overriding a method throwing an Exception?

The following are some of the rules that have to be followed while overriding method throwing Exception:

Rule 1: If the parent class method is not throwing any exceptions, then the overridden child class method should not throw checked exceptions. But it can throw an unchecked exception. Consider an example that demonstrates this- We have 2 classes - ParentDemo and ChildDemo where the latter is the subclass of the ParentDemo class. We have the doThis() the method that is overridden in the ChildDemo class. The overridden method may only throw an unchecked exception. The below example is valid since IllegalArgumentException is an unchecked exception.

Rule 2: If the parent class method is throwing one or more checked exceptions, then the overridden method in the child class can throw any unchecked exceptions or any exceptions that are the same as checked exceptions of the parent method or the subclasses of those checked exceptions. Consider the below example code:

In this example, the doThis() method throws few exceptions than the parent method and the doThat() method throws a greater number of exceptions, however, the scope of the exceptions is not greater than the parent exceptions. If we try to throw a checked exception that was not declared in the parent method or we throw an exception that has a broader scope, then it results in a compilation error. For example, the below code is not valid as the parent method throws a FileNotFoundException exception and the child method throws IOException which is broader in scope as it is the parent class of FileNotFoundException :

Rule 3: If the parent class method has a throws clause having unchecked exceptions, then the overriding child method can throw any number of unchecked exceptions even if they are not related to each other. Consider the below example. While the parent class doThis() method threw only 1 unchecked exception which is IllegalArgumentException , the child class could throw multiple unchecked exceptions as shown below:

15. What are some of the best practices to be followed while dealing with Java Exception Handling?

The following are some of the best practices that have to be followed while developing Exception Handling in Java:

  • Use Specific Exception as much as possible for the sake of better messages and easier debugging.
  • Throw Exceptions early in the program. This follows the Fail-Fast approach to development.
  • Catch Exceptions late in the program, i.e, the caller has to handle the exceptions.
  • If you are using Java 7 and above versions, make use of the feature of the try-with-resources block to close the resources properly. In this way, we do not have to remember to ensure that all resources have been closed in the finally block.
  • Always log the exception messages with meaningful messages. This helps in easier debugging.
  • Use multiple catches that follow the rule of most specific exceptions at the top and the most generic exceptions at the bottom.
  • If the exception types provided by Java do not match your use case, make sure to use custom exceptions with meaningful error messages.
  • While creating custom messages, the naming convention of ending the exception name with Exception has to be followed.
  • Whenever your method throws any exception, document this using the Javadoc and describe that briefly using the @throws parameter.
  • Since exceptions are costly, be responsible while throwing them. Only throw them if it makes sense.

Exception handling is a very important technique for handling abnormal errors or failures that could happen at run time. It makes the program more robust and immune to failure scenarios thereby providing a better user experience to the users. Hence, software developers need to know how to manage and handle exceptions. In this article, we have seen what are the most commonly asked interview questions for both freshers and experienced software developers.

Useful Resources

  • https://www.interviewbit.com/problems/exception-handling/
  • https://www.interviewbit.com/problems/try-catch-block/
  • https://www.scaler.com/topics/java/error-vs-exception-in-java/
  • https://www.interviewbit.com/technical-interview-questions/

Which of the following is false about the finally block?

Which statement is used to catch all types of exceptions?

What is the superclass for error and exception classes in Java?

Which activity is typically written within the try block?

Which block always executes whether or not an exception occurs?

Which of these methods returns the description of an exception?

Which exception detects argument error in Java?

Which exception has to be handled if the close() method is called on a connection object?

What happens when the following statements are run?

A. System.out.println(1/0); B. System.out.println(2.0/0);

What happens if the below code is executed?

  • Privacy Policy

instagram-icon

  • Practice Questions
  • Programming
  • System Design
  • Fast Track Courses
  • Online Interviewbit Compilers
  • Online C Compiler
  • Online C++ Compiler
  • Online Java Compiler
  • Online Javascript Compiler
  • Online Python Compiler
  • Interview Preparation
  • Java Interview Questions
  • Sql Interview Questions
  • Python Interview Questions
  • Javascript Interview Questions
  • Angular Interview Questions
  • Networking Interview Questions
  • Selenium Interview Questions
  • Data Structure Interview Questions
  • Data Science Interview Questions
  • System Design Interview Questions
  • Hr Interview Questions
  • Html Interview Questions
  • C Interview Questions
  • Amazon Interview Questions
  • Facebook Interview Questions
  • Google Interview Questions
  • Tcs Interview Questions
  • Accenture Interview Questions
  • Infosys Interview Questions
  • Capgemini Interview Questions
  • Wipro Interview Questions
  • Cognizant Interview Questions
  • Deloitte Interview Questions
  • Zoho Interview Questions
  • Hcl Interview Questions
  • Highest Paying Jobs In India
  • Exciting C Projects Ideas With Source Code
  • Top Java 8 Features
  • Angular Vs React
  • 10 Best Data Structures And Algorithms Books
  • Best Full Stack Developer Courses
  • Best Data Science Courses
  • Python Commands List
  • Data Scientist Salary
  • Maximum Subarray Sum Kadane’s Algorithm
  • Python Cheat Sheet
  • C++ Cheat Sheet
  • Javascript Cheat Sheet
  • Git Cheat Sheet
  • Java Cheat Sheet
  • Data Structure Mcq
  • C Programming Mcq
  • Javascript Mcq

1 Million +

  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot

Built-in Exceptions in Java with examples

  • Top 5 Exceptions in Java with Examples
  • Types of Exception in Java with Examples
  • File exists() method in Java with examples
  • Constructor getGenericExceptionTypes() method in Java with Examples
  • Best Practices to Handle Exceptions in Java
  • ClosedChannelException in Java with Examples
  • How to Solve Class Cast Exceptions in Java?
  • Chained Exceptions in Java
  • Scanner ioException() method in Java with Examples
  • Class forName() method in Java with Examples
  • User-defined Custom Exception in Java
  • Formatter ioException() method in Java with Examples
  • Array Index Out Of Bounds Exception in Java
  • Exceptions in Android with Example
  • exception::bad_exception in C++ with Examples
  • Exception Header in C++ With Examples
  • User-defined Exceptions in Python with Examples
  • Exception Handling in Kotlin with Examples
  • Built-in Exceptions in Python

Types of Exceptions in Java Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are suitable to explain certain error situations. Below is the list of important built-in exceptions in Java. 

Examples of Built-in Exception:

1. Arithmetic exception : It is thrown when an exceptional condition has occurred in an arithmetic operation. 

2. ArrayIndexOutOfBounds Exception : It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array. 

public static void main(String args[]) { try {

// Following file does not exist File file = new File("E:// file.txt");

FileReader fr = new FileReader(file); } catch (FileNotFoundException e) { System.out.println("File does not exist"); } } }

Output: 

3. ClassNotFoundException : This Exception is raised when we try to access a class whose definition is not found. 

4. FileNotFoundException : This Exception is raised when a file is not accessible or does not open. 

5. IOException : It is thrown when an input-output operation failed or interrupted 

6. InterruptedException : It is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted. 

7. NoSuchMethodException : t is thrown when accessing a method which is not found. 

8. NullPointerException : This exception is raised when referring to the members of a null object. Null represents nothing 

9. NumberFormatException : This exception is raised when a method could not convert a string into a numeric format. 

10. StringIndexOutOfBoundsException : It is thrown by String class methods to indicate that an index is either negative than the size of the string. 

Some other important Exceptions

1. ClassCastException  

2. StackOverflowError  

3. NoClassDefFoundError  

4. ExceptionInInitializerError  

Code 1: 

Code 2 : 

Explanation : The above exception occurs whenever while executing static variable assignment and static block if any Exception occurs.

5. IllegalArgumentException  

Explanation: The Exception occurs explicitly either by the programmer or by API developer to indicate that a method has been invoked with Illegal Argument.

6. IllegalThreadStateException  

Explanation : The above exception rises explicitly either by programmer or by API developer to indicate that a method has been invoked at wrong time.

7. AssertionError  

Explanation : The above exception rises explicitly by the programmer or by API developer to indicate that assert statement fails.

IllegalArgumentException: This exception is thrown when an illegal argument is passed to a method. For example:

Filenotfoundexception: this exception is thrown when a file cannot be found. for example:, please login to comment..., similar reads.

  • Java-Exceptions

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

{{ activeMenu.name }}

  • Python Courses
  • JavaScript Courses
  • Artificial Intelligence Courses
  • Data Science Courses
  • React Courses
  • Ethical Hacking Courses
  • View All Courses

Fresh Articles

TripleTen Data Science Bootcamp: Insider Review

  • Python Projects
  • JavaScript Projects
  • Java Projects
  • HTML Projects
  • C++ Projects
  • PHP Projects
  • View All Projects

How To Create A Professional Portfolio Page Using HTML

  • Python Certifications
  • JavaScript Certifications
  • Linux Certifications
  • Data Science Certifications
  • Data Analytics Certifications
  • Cybersecurity Certifications
  • View All Certifications

DataCamp’s Certifications To Get You Job-Ready: Insider Review

  • IDEs & Editors
  • Web Development
  • Frameworks & Libraries
  • View All Programming
  • View All Development
  • App Development
  • Game Development
  • Courses, Books, & Certifications
  • Data Science
  • Data Analytics
  • Artificial Intelligence (AI)
  • Machine Learning (ML)
  • View All Data, Analysis, & AI
  • Networking & Security
  • Cloud, DevOps, & Systems
  • Recommendations
  • Crypto, Web3, & Blockchain
  • User-Submitted Tutorials
  • View All Blog Content
  • JavaScript Online Compiler
  • HTML & CSS Online Compiler
  • Certifications
  • Programming
  • Development
  • Data, Analysis, & AI
  • Online JavaScript Compiler
  • Online HTML Compiler

Don't have an account? Sign up

Forgot your password?

Already have an account? Login

Have you read our submission guidelines?

Go back to Sign In

assignment questions on exception handling in java

Top 80 Java Interview Questions and Answers [2024]

To land the job, it helps to review common and challenging Java interview questions. After all, the class-based, general-purpose, object-oriented programming language is one of the most widely used programming languages in the world .

We prepared these Java interview questions with answers from experts. Expect to cover the basics with beginner-friendly topics and much more advanced challenges with specific code to help professional Software Developers and Android Applications Developers. 

Remember that, with a plethora of great features , the programming language is preferred not only by seasoned experts but also by those new to the programming world. Our interview questions start with basic Java concepts and progress to much more difficult challenges.

Whether you're seeking a new gig or hiring to expand your team, read on to review the best Java interview questions for 2024.

  • Top Java Interview Questions and Answers

We also recommend you brush up on your Java skills with this Java Cheat Sheet before starting your Java interview preparation. 

We have divided these interview questions into several sections. Check the breakdown below to review basic, advanced, OOPs, exception handling, and programming Java interview questions. We also have specific examples of code. Review the coding Java interview questions section for reference.

Basic Java Interview Questions

1. what is java.

Java is an object-oriented, high-level, general-purpose programming language originally designed by James Gosling and further developed by the Oracle Corporation. It is one of the most popular programming languages in the world . 

2. What is the Java Virtual Machine? 

Java Virtual Machine

JVM is a program that interprets the intermediate Java byte code and generates the desired output. It is because of bytecode and JVM that programs written in Java are highly portable. 

3. What are the features of Java?

The following are the various features of the Java programming language:

  • High Performance: Using a JIT (Just-In-Time) compiler allows high performance in Java. The JIT compiler converts the Java bytecode into machine language code, which then gets executed by the JVM.
  • Multi-threading: A thread is a flow of execution. The JVM creates a thread which is called the main thread. Java allows the creation of several threads using either extending the thread class or implementing the Runnable interface.
  • OOPs Concepts: Java follows various OOPs concepts , namely abstraction, encapsulation, inheritance, object-oriented, and polymorphism
  • Platform Independency: Java makes use of the Java Virtual Machine or JVM, which allows a single Java program to operate on multiple platforms without any modifications.

You may want to check out detailed explanations of Java features here . 

4. How does Java enable high performance?

In Just-in-Time compilation, the required code is executed at run time. Typically, it involves translating bytecode into machine code and then executing it directly. It allows for high performance. The JIT compiler is enabled by default in Java and gets activated as soon as a method is called. 

It then compiles the bytecode of the Java method into native machine code. 

After that, the JVM calls the compiled code directly instead of interpreting it.

5. What are the differences between JVM, JRE, and JDK?

6. what is the jit compiler.

JIT compiler runs after the program is executed and compiles the code into a faster form, hosting the CPU's native instructing set. JIT can access dynamic runtime information, whereas a standard compiler doesn't and can make better optimizations like inlining functions that are used frequently. 

7. What are Java IDEs?

A Java IDE is a software that allows Java developers to easily write as well as debug Java programs. It is basically a collection of various programming tools, accessible via a single interface, and several helpful features, such as code completion and syntax highlighting. 

Codenvy, Eclipse, and NetBeans are some of the most popular Java IDEs .

8. Java is a platform-independent language. Why?

Java does not depend on any particular hardware or software because it is compiled by the compiler and then converted into byte code. Byte code is platform-independent and can run on multiple systems. The only requirement is that Java needs a runtime environment, i.e., JRE, which is a set of tools used for developing Java applications.

9. Explain Typecasting.

The concept of assigning a variable of one data type to a variable of another data type. This is not possible for the boolean data type. There are two types: implicit and explicit.

10. What are the different types of typecasting?

types of typecasting

The different types of typecasting are:

  • Implicit: Storing values from a smaller data type to the larger data type. It is automatically done by the compiler.
  • Explicit: Storing the value of a larger data type into a smaller data type. This results in information loss:
  • Truncation: While converting a value from a larger data type to a smaller data type, the extra data will be truncated. This code example explains it : 

After execution, the variable i will contain only 3 and not the decimal portion. 

  • Out of Range: Typecasting does not allow assigning value more than its range; if that happens then the data is lost in such cases. This code example explains it: 

long l = 123456789;

byte b = ( byte ) l; // byte is of not the same range as long so there will be loss of data.

11. Explain access modifiers in Java.

Access modifiers are predefined keywords in Java that are used to restrict the access of a class, method, constructor, and data member in another class. Java supports four access modifiers:

12. What are the default values for local variables?

The local variables are not initialized to any default value, neither primitives nor object references.

OOPs Java Interview Questions

13. what is object-oriented programming .

OOPs is a programming paradigm centered around objects rather than functions. It is not a tool or a programming language, it is a paradigm that was designed to overcome the flaws of procedural programming . 

There are many languages that follow OOPs concepts — some popular ones are Java, Python, and Ruby. Some frameworks also follow OOPs concepts, such as Angular.

14. Explain the OOPs concepts.

The following are the various OOPS Concepts:

  • Abstraction: Representing essential features without the need to give out background details. The technique is used for creating a new suitable data type for some specific application.
  • Aggregation: All objects have their separate lifecycle, but ownership is present. No child object can belong to some other object except for the parent object.
  • Association: The relationship between two objects, where each object has its separate lifecycle. There is no ownership.
  • Class: A group of similar entities.
  • Composition: Also called the death relationship, it is a specialized form of aggregation. Child objects don't have a lifecycle. As such, they automatically get deleted if the associated parent object is deleted.
  • Encapsulation: Refers to the wrapping up of data and code into a single entity. This allows the variables of a class to be only accessible by the parent class and no other classes.
  • Inheritance: When an object acquires the properties of some other object, it is called inheritance. It results in the formation of a parent-child relationship amongst classes involved. This offers a robust and natural mechanism of organizing and structuring software.
  • Object: Denotes an instance of a class. Any class can have multiple instances. An object contains the data as well as the method that will operate on the data
  • Polymorphism: Refers to the ability of a method, object, or variable to assume several forms.

Decision Making Java Interview Questions

15. Differentiate between break and continue.

Classes, objects, and methods java interview questions, 16. what is an object.

An instance of a Java class is known as an object. Two important properties of a Java object are behavior and state . An object is created as soon as the JVM comes across the new keyword.

17. Define classes in Java. 

A class is a collection of objects of similar data types. Classes are user-defined data types and behave like built-in types of a programming language. 

Syntax of a class: 

Example of Class:

18. What are static methods and variables?

A class has two sections: one declares variables, and the other declares methods. These are called instance variables and instance methods, respectively. They are termed so because every time a class is instantiated, a new copy of each of them is created. 

Variables and methods can be created that are common to all objects and accessed without using a particular object by declaring them static. Static members are also available to be used by other classes and methods. 

19. What do you mean by Constructor?

A constructor is a method that has the same name as that of the class to which it belongs. As soon as a new object is created, a constructor corresponding to the class gets invoked. Although the user can explicitly create a constructor, it is created on its own as soon as a class is created. This is known as the default constructor. Constructors can be overloaded.

If an explicitly-created constructor has a parameter, then it is necessary to create another constructor without a parameter.

20. What are local variables and instance variables?

Variables that are only accessible to the method or code block in which they are declared are known as local variables. Instance variables, on the other hand, are accessible to all methods in a class. 

While local variables are declared inside a method or a code block, instance variables are declared inside a class but outside a method. Even when not assigned, instance variables have a value that can be null, 0, 0.0, or false. This isn't the case with local variables that need to be assigned a value, where failing to assign a value will yield an error. Local variables are automatically created when a method is called and destroyed as soon as the method exits. For creating instance variables, the new keyword must be used.

21. What is Method Overriding?

Method Overriding

Method overriding in Java allows a subclass to offer a specific implementation of a method that has already been provided by its parent or superclass. Method overriding happens if the subclass method and the Superclass method have:

  • The same name
  • The same argument
  • The same return type

22. What is Overloading?

Overloading is the phenomenon when two or more different methods (method overloading) or operators (operator overloading) have the same representation. For example, the + operator adds two integer values but concatenates two strings. Similarly, an overloaded function called Add can be used for two purposes

  • To add two integers
  • To concatenate two strings

Unlike method overriding, method overloading requires two overloaded methods to have the same name but different arguments. The overloaded functions may or may not have different return types.

23. What role does the final keyword play in Java? What impact does it have on a variable, method, and class?

The final keyword in Java is a non-access modifier that applies only to a class, method, or variable. It serves a different purpose based on the context where it is used.

  • With a class: When a class is declared as final, then it is disabled from being subclassed i.e., no class can extend the final class.
  • With a method: Any method accompanying the final keyword is restricted from being overridden by the subclass.
  • With a variable: A variable followed by the final keyword is not able to change the value that it holds during the program execution. So, it behaves like a constant.

Arrays, Strings and Vectors Java Interview Questions

24. draw a comparison between array and arraylist..

An array necessitates stating the size during the time of declaration, while an array list doesn't necessarily require size as it changes size dynamically. To put an object into an array, there is the need to specify the index. However, no such requirement is in place for an array list. While an array list is parameterized, an array is not parameterized.

25. What are the differences between String, Stringbuilder, and Stringbuffer?

String variables are stored in a constant string pool. With the change in the string reference, it becomes impossible to delete the old value. For example, if a string has stored a value "Old," then adding the new value "New" will not delete the old value. It will still be there, however, in a dormant state. In a Stringbuffer, values are stored in a stack. With the change in the string reference, the new value replaces the older value. The Stringbuffer is synchronized (and therefore, thread-safe) and offers slower performance than the StringBuilder, which is also a Stringbuffer but is not synchronized. Hence, performance is faster in Stringbuilder than the Stringbuffer.

26. What is the String Pool?

The string pool is a collection of strings stored in the heap memory refers to. Whenever a new object is created, it is checked if it is already present in the string pool. If it is already present, then the same reference is returned to the variable, otherwise a new object is created in the string pool, and the respective reference is returned.

  • Advanced Java Interview Questions

Interfaces and Abstract Classes Java Interview Questions

27. what do you know about interfaces.

A Java interface is a template that has only method declarations and not method implementations. It is a workaround for achieving multiple inheritances in Java. Some worth remembering important points regarding Java interfaces are:

  • A class that implements the interface must provide an implementation for all methods declared in the interface.
  • All methods in an interface are internally public abstract void.
  • All variables in an interface are internally public static final.
  • Classes do not extend but implement interfaces.

28. How is an Abstract class different from an Interface?

There are several differences between an Abstract class and an Interface in Java, summed up as follows:

  • Constituents: An abstract class contains instance variables, whereas an interface can contain only constants.
  • Constructor and Instantiation: While an interface has neither a constructor nor it can be instantiated, an abstract class can have a default constructor that is called whenever the concrete subclass is instantiated.
  • Implementation of Methods – All classes that implement the interface need to provide an implementation for all the methods contained by it. A class that extends the abstract class, however, doesn't require implementing all the methods contained in it. Only abstract methods need to be implemented in the concrete subclass.
  • Type of Methods: Any abstract class has both abstract as well as non-abstract methods. Interface, on the other hand, has only a single abstract method.

29. Please explain Abstract class and Abstract method.

An abstract class in Java is a class that can't be instantiated. Such a class is typically used for providing a base for subclasses to extend as well as implementing the abstract methods and overriding or using the implemented methods defined in the abstract class. 

To create an abstract class, it needs to be followed by the abstract keyword. Any abstract class can have both abstract as well as non-abstract methods. A method in Java that only has the declaration and not implementation is known as an abstract method. Also, an abstract method name is followed by the abstract keyword. Any concrete subclass that extends the abstract class must provide an implementation for abstract methods.

30. What is multiple inheritance? Does Java support multiple inheritance? If not, how can it be achieved?

If a subclass or child class has two parent classes, that means it inherits the properties from two base classes; it has multiple inheritances. Java does not have multiple inheritances as in case the parent classes have the same method names. Then at runtime, it becomes ambiguous, and the compiler is unable to decide which method to execute from the child class.

Packages Java Interview Questions

31. what are packages in java state some advantages..

packages in Java

Packages are Java's way of grouping a variety of classes and/or interfaces together. The functionality of the objects decides how they are grouped. Packagers act as "containers" for classes.

Enlisted below are the advantages of Packages:

  • Classes of other programs can be reused.
  • Two classes with the same can exist in two different packages.
  • Packages can hide classes, thus denying access to certain programs and classes meant for internal use only.
  • They also separate design from coding.

Multithreading Java Interview Questions

32. how do you make a thread in java give examples..

To make a thread in Java, there are two options:

  • Extend the Thread Class : The thread is available in the java.lang.Thread class. To make a thread, you need to extend a thread class and override the run method. For example,

A disadvantage of using the thread class is that it becomes impossible to extend any other classes.

Nonetheless, it is possible to overload the run() method in the class

  • Implement Runnable Interface: Another way of making a thread in Java is by implementing a runnable interface. For doing so, there is the need to provide the implementation for the run() method that is defined as follows:

33. Why do we use the yield() method?

The yield() method belongs to the thread class. It transfers the currently running thread to a runnable state and also allows the other threads to execute. In other words, it gives equal priority threads a chance to run. Because yield() is a static method, it does not release any lock.

34. Explain the thread lifecycle in Java.

thread lifecycle in Java.

The thread lifecycle has the following states and follows the following order:

  • New: In the very first state of the thread lifecycle, the thread instance is created, and the start() method is yet to be invoked. The thread is considered alive now.
  • Runnable: After invoking the start() method, but before invoking the run() method, a thread is in the runnable state. A thread can also return to the runnable state from waiting or sleeping.
  • Running: The thread enters the running state after the run() method is invoked. This is when the thread begins execution.
  • Non-Runnable: Although the thread is alive, it is not able to run. Typically, it returns to the runnable state after some time.
  • Terminated: The thread enters the terminated state once the run() method completes its execution. It is not alive now.

35. When is the Runnable interface preferred over thread class and vice-versa?

In Java, it is possible to extend only one class. Hence, the thread class is only extended when no other class needs to be extended. If it is required for a class to extend some other class than the thread class, then we need to use the Runnable interface.

36. Draw a comparison between notify() and notifyAll() methods.

The notify() method is used for sending a signal to wake up a single thread in the waiting pool. Contrarily, the notifyAll() method is used for sending a signal to wake up all threads in a waiting pool.

37. How will you distinguish processes from threads?

There are several fundamental differences between a process and a thread, stated as follows:

  • Definition: A process is an executing instance of a program whereas, a thread is a subset of a process.
  • Changes: A change made to the parent process doesn't affect child processes. However, a change in the main thread can yield changes in the behavior of other threads of the same process.
  • Communication – While processes require inter-process communication for communicating with sibling processes, threads can directly communicate with other threads belonging to the same process.
  • Control: Processes are controlled by the operating system and can control only child processes. On the contrary, threads are controlled by the programmer and are capable of exercising control over threads of the same process to which they belong.
  • Dependence: Processes are independent entities while threads are dependent entities
  • Memory: Threads run in shared memory spaces, but processes run in separate memory spaces.

38. What is the join() method? Give an example.

We use the join() method for joining one thread with the end of the currently running thread. It is a non-static method and has an overloaded version. Consider the example below:

The main thread starts execution in the example mentioned above. As soon as the execution reaches the code t.start(), then the thread t starts its stack for execution. The JVM switches between the main thread and the thread there. Once the execution reaches the t.join(), then the thread t alone is executed and allowed to complete its task. Afterwards, the main thread resumes execution.

39. How do you make a thread stop in Java?

There are three methods in Java to stop the execution of a thread:

  • Blocking: This method is used to put the thread in a blocked state. The execution resumes as soon as the condition of the blocking is met. For instance, the ServerSocket.accept() is a blocking method that listens for incoming socket connections and resumes the blocked thread only when a connection is made.
  • Sleeping: This method is used for delaying the execution of the thread for some time. A thread upon which the sleep() method is used is said to enter the sleep state. It enters the runnable state as soon as it wakes up i.e., the sleep state is finished. The time for which the thread needs to enter the sleep state is mentioned inside the braces of the sleep() method. It is a static method.
  • Waiting: Although it can be called on any Java object, the wait() method can only be called from a synchronized block.

Exception Handling Java Interview Questions

40. what are the various types of exceptions how do you handle them.

Java has provision for two types of exceptions:

  • Checked Exceptions: Classes that extend the Throwable class, except Runtime exception and Error, are called checked exceptions. Such exceptions are checked by the compiler during the compile time. These types of exceptions must either have appropriate try/catch blocks or be declared using the throws keyword. ClassNotFoundException is a checked exception.
  • Unchecked Exceptions: Such exceptions aren't checked by the compiler during the compile time. As such, the compiler doesn't necessitate handling unchecked exceptions. Arithmetic Exception and ArrayIndexOutOfBounds Exception are unchecked exceptions.

Exceptions in Java are handled in two ways:

Declaring the throws keyword: We can declare the exception using throws keyword at the end of the method. For example:

Using try/catch: Any code segment that is expected to yield an exception is surrounded by the try block. Upon the occurrence of the exception, it is caught by the catch block that follows the try block. For example:

41. Draw the Java Exception Hierarchy.

Java Exception Hierarchy

42. Is it possible to write multiple catch blocks under a single try block?

Yes, it is possible to write several catch blocks under a single try block. However, the approach needs to be from specific to general. The following example demonstrates it:

43. How does the throw keyword differ from the throws keyword?

While the throws keyword allows declaring an exception, the throw keyword is used to explicitly throw an exception. 

Checked exceptions can't be propagated with throw only, but throws allow doing so without the need for anything else. 

The throws keyword is followed by a class, whereas the throw keyword is followed by an instance. The throw keyword is used within the method, but the throws keyword is used with the method signature. 

Furthermore, it is not possible to throw multiple exceptions, but it is possible to declare multiple exceptions.

44. Explain various exceptions handling keywords in Java.

There are two crucial exception handling keywords in Java, followed by the third keyword final, which may or may not be used after handling exceptions.

If and when a code segment has chances of having an abnormality or an error, it is placed within a try block. When the exception is raised, it is handled and caught by the catch block.

The try block must have a catch() or a final() or both blocks after it.

When an exception is raised in the try block, it is handled in the catch block.

This block is executed regardless of the exception. It can be placed either after try{} or catch {} block.

45. Explain exception propagation.

The method at the top of the stack throws an exception if it is not caught. It moves to the next method and goes on until caught.

The stack of the above code is:

If an exception occurred in the add() method is not caught, then it moves to the method addition(). It is then moved to the main() method, where the flow of execution stops. It is called Exception Propagation.

File Handling Java Interview Questions

46. is an empty file name with .java extension a valid file name.

Yes, Java permits us to save our java file by .java only. It is compiled by javac and run by the java class name. Here’s an example:

To compile: javac.java

To run: Java Any

Collections Java Interview Questions

47. what are collections what are their constituents.

A group of objects in Java is known as collections. Java.util package contains, along with date and time facilities, internationalization, legacy collection classes, etc., the various classes and interfaces for collecting. Alternatively, collections can be considered as a framework designed for storing the objects and manipulating the design in which the objects are stored. You can use collections to perform the following operations on objects:

  • Manipulation

Following are the various constituents of the collections framework:

  • Classes: Array List, Linked List, Lists, and Vector
  • Interfaces: Collection, List, Map, Queue, Set, Sorted Map, and Sorted Set
  • Maps: HashMap, HashTable, LinkedHashMap, and TreeMap
  • Queues: Priority Queue
  • Sets: Hash Set, Linked Hash Set, and Tree Set

48. How do you differentiate HashMap and HashTable?

HashMap in Java is a map-based collection class, used for storing key & value pairs. It is denoted as HashMap<Key, Value> or HashMap<K, V> HashTable is an array of a list, where each list is called a bucket. 

Values contained in a HashTable are unique and depend on the key. Methods are not synchronized in HashMap, while key methods are synchronized in HashTable. 

However, HashMap doesn't have thread safety, while HashTable has the same. 

For iterating values, HashMap uses an iterator and HashTable uses an enumerator. HashTable doesn't allow anything that is null, while HashMap allows one null key and several null values. 

In terms of performance, HashTable is slow. Comparatively, HashMap is faster.

49. What is a Map and what are the types?

A Java Map is an object that maps keys to values. It can't contain duplicate keys, and each key can map to only one value. In order to determine whether two keys are the same or distinct, Map makes use of the equals() method. There are 4 types of Map in Java, described as follows:

  • HashMap: It is an unordered and unsorted map and hence, is a good choice when there is no emphasis on the order. A HashMap allows one null key and multiple null values and doesn't maintain any insertion order.
  • HashTable: Doesn't allow anything null and has methods that are synchronized. As it allows for thread safety, the performance is slow.
  • LinkedHashMap: Slower than a HashMap but maintains insertion order and has a faster iteration.
  • TreeMap: A sorted Map providing support for constructing a sort order using a constructor.

50. What is a Priority Queue?

A priority queue, like a regular queue, is an abstract data type, but it has a priority associated with each element contained by it. 

The element with the high priority is served before the element with low priority in a priority queue. Elements in a priority queue are ordered either according to the comparator or naturally. The order of the elements in a priority queue represents their relative priority.

51. What is a Set? Explain the types in Java Collections.

In Java, a set is a collection of unique objects. It uses the equals() method to determine whether two objects are the same or not. The various types of set in Java Collections are:

  • Hash Set: An unordered and unsorted set that uses the hash code of the object for adding values. Used when the order of the collection isn't important
  • Linked Hash Set: This is an ordered version of the hash set that maintains a doubly-linked list of all the elements. Used when iteration order is mandatory. Insertion order is the same as that of how elements are added to the Set.
  • Tree Set: One of the two sorted collections in Java, it uses Read-Black tree structure and ensures that the elements are present in the ascending order.

52. What is ordered and sorted when it comes to collections?

  • Ordered: Values are stored in a collection in a specific order, but the order is independent of the value. Example: List
  • Sorted: The collection has an order which is dependent on the value of an element. Example: SortedSet

Miscellaneous Java Interview Questions 

53. what are the various types of garbage collectors in java.

The Java programming language has four types of garbage collectors:

  • Serial Garbage Collector: Using only a single thread for garbage collection, the serial garbage collector works by holding all the application threads. It is designed especially for single-threaded environments. Because serial garbage collector freezes all application threads while performing garbage collection, it is most suitable for command-line programs only. For using the serial garbage collector, one needs to turn on the -XX:+UseSerialGC JVM argument.
  • Parallel Garbage Collector: Also known as the throughput collector, the parallel garbage collector is the default garbage collector of the JVM. It uses multiple threads for garbage collection, and like a serial garbage collector freezes all application threads during garbage collection.
  • CMS Garbage Collector: Short for Concurrent Mark Sweep, CMS garbage collector uses multiple threads for scanning the heap memory for marking instances for eviction, followed by sweeping the marked instances. There are only two scenarios when the CMS garbage collector holds all the application threads:
  • When marking the referenced objects in the tenured generation space.
  • If there is a change in the heap memory while performing the garbage collection, CMS garbage collector ensures better application throughput over parallel garbage collectors by using more CPU resources. For using the CMS garbage collector, the XX:+USeParNewGC JVM argument needs to be turned on.
  • G1 Garbage Collector: Used for large heap memory areas, G1 garbage collector works by separating the heap memory into multiple regions and then executing garbage collection in them in parallel. Unlike the CMS garbage collector that compacts the memory on STW (Stop The World) situations , G1 garbage collector compacts the free heap space right after reclaiming the memory. Also, the G1 garbage collector prioritizes the region with the most garbage. Turning on the –XX:+UseG1GC JVM argument is required for using the G1 garbage collector.

54. What do you understand by synchronization? What is its most significant disadvantage?

If several threads try to access a single block of code, then there is an increased chance of producing inaccurate results. Synchronization is used to prevent this. Using the synchronization keyword makes a thread need a key to access the synchronized code. Simply, synchronization allows only one thread to access a block of code at a time. Each Java object has a lock, and every lock has only one key. A thread can access a synchronized method only if it can get the key to the lock of the object. The following example demonstrates synchronization:

Note : It is recommended to avoid implementing synchronization for all methods. This is because when only one thread can access the synchronized code, the next thread needs to wait. Consequently, it results in slower performance of the program.

55. What is the difference between execute(), executeQuery(), and executeUpdate()?

  • execute(): Used for executing an SQL query. It returns TRUE if the result is a ResultSet, like running Select queries, and FALSE if the result is not a ResultSet, such as running an Insert or an Update query.
  • executeQuery(): Used for executing Select queries. It returns the ResultSet, which is not null, even if no records are matching the query. The executeQuery() method must be used when executing select queries so that it throws the java.sql.SQLException with the 'executeQuery method cannot be used for update' message when someone tries to execute an Insert or Update statement.
  • executeUpdate(): Used for executing Delete/Insert/Update statements or DDL statements that return nothing. The output varies depending on whether the statements are Data Manipulation Language (DML) statements or Data Definition Language (DDL) statements. The output is an integer and equals the total row count for the former case, and 0 for the latter case.

Note : The execute() method needs to be used only in a scenario when there is no certainty about the type of statement. In all other cases, either use executeQuery() or executeUpdate() method.

56. Provide an example of the Hibernate architecture.

Hibernate architecture

57. Could you demonstrate how to delete a cookie in JSP with a code example?

The following code demonstrates deleting a cookie in JSP:

58. Write suitable code examples to demonstrate the use of final, final, and finalize.

Final:  The final keyword is used for restricting a class, method, and variable. A final class can't be inherited, a final method is disabled from overriding, and a final variable becomes a constant i.e., its value can't be changed.

Finally: Any code inside the final block will be executed, irrespective of whether an exception is handled or not.

Finalize: The finalize method performs the clean up just before the object is garbage collected.

59. What purpose does the Volatile variable serve?

The value stored in a volatile variable is not read from the thread's cache memory but from the main memory. Volatile variables are primarily used during synchronization.

60. Please compare serialization and deserialization.

Serialization is the process by which Java objects are converted into the byte stream. 

Deserialization is the exact opposite process of serialization where Java objects are retrieved from the byte stream.

 A Java object is serialized by writing it to an ObjectOutputStream and deserialized by reading it from an ObjectInputStream.

61. What is OutOfMemoryError?

Typically, the OutOfMemoryError exception is thrown when the JVM is not able to allocate an object due to running out of memory. In such a situation, no memory could be reclaimed by the garbage collector. 

There can be several reasons that result in the OutOfMemoryError exception, of which the most notable ones are:

  • Holding objects for too long
  • Trying to process too much data at the same time
  • Using a third-party library that caches strings
  • Using an application server that doesn't perform a memory cleanup post the deployment
  • When a native allocation can't be satisfied

62. Explain public static void main(String args[ ]) in Java

The execution Java program starts with public static void main(String args[ ]), also called the main() method.

  • public: It is an access modifier defining the accessibility of the class or method. Any class can access the main() method defined public in the program.
  • static: The keyword indicates the variable, or the method is a class method. The method main() is made static so that it can be accessed without creating the instance of the class. When the method main() is not made static, the compiler throws an error because the main() is called by the JVM before any objects are made, and only static methods can be directly invoked via the class.
  • void: It is the return type of the method. Void defines the method that does not return any type of value.
  • main: JVM searches this method when starting the execution of any program, with the particular signature only.
  • String args[]: The parameter passed to the main method.

Java Programming Masterclass Updated to Java 17

63. What are wrapper classes in Java?

Wrapper classes are responsible for converting the Java primitives into the reference types (objects). A class is dedicated to every primitive data type. They are known as wrapper classes because they wrap the primitive data type into an object of that class. It is present in the Java.lang package. The table below displays the different primitive types and wrapper classes.

64. Explain the concept of boxing, unboxing, autoboxing, and auto unboxing.

  • Boxing: The concept of putting a primitive value inside an object is called boxing.
  • Unboxing: Getting the primitive value from the object.
  • Autoboxing: Assigning a value directly to an integer object.
  • Auto unboxing: Getting the primitive value directly into the integer object.

65. Define the Singleton class. How can a class be made Singleton?

A Singleton class allows only one instance of the class to be created. A class can be made singleton with the following steps:

  • Creating a static instance of the class with the class.
  • By not allowing the user to create an instance with default constructor by defining a private constructor.
  • Create a static method to return the object of an instance of A.

66. What if the public static void is replaced by static public void, will the program still run?

Yes, the program would compile and run without any errors as the order of the specifiers doesn't matter.

67. What is the difference between == and equals()?

68. why don't we use pointers in java.

Pointers are considered to be unsafe, and increase the complexity of the program, adding the concept of pointers can be contradicting. Also, JVM is responsible for implicit memory allocation; thus, to avoid direct access to memory by the user, pointers are discouraged in Java.

69. What is the difference between this() and super()?

Java coding interview questions .

Apart from having good knowledge about concepts of Java programming, you are also tested for your skills in coding in Java programming language. The following are Java coding interview questions that are relevant for freshers and are quite popular amongst Java programming interviews.

70. Take a look at the two code snippets below. What is the important difference between the two?

Code snippet i. is an example of method overloading while the code snippet ii. demonstrates method overriding.

71. Write a program for string reversal without using an inbuilt function.

72. write a program to delete duplicates from an array., 73. write a program to reverse a number., 74. write a program that implements binary search., 75. write a program to check if a number is prime., 76. write a program to print fibonacci series., 77. write a program to check if the given string is a palindrome., 78. write a program to print the following pattern., 79. write a program to swap two numbers., 80. write a program to check if the given number is an armstrong number..

These core Java Interview Questions and Java Programming Interview Questions are a great way to prepare you for the interview. Review the answers, including the coding examples, and put your best foot forward.

Please note that we also provided a PDF for your preparation so that you can download and learn and prepare on the go: 

Download Java Interview Questions PDF

Prefer on-demand videos? Check out this course for further reading and preparation for a Java-based interview: Java Interview Guides: 200+ Interview Question and Answer

Otherwise, we recommend this book to help you succeed in your future Java interviews: Elements of Programming Interviews in Java: The insider guide second edition

  • Frequently Asked Questions

1. What are the basic Java questions asked in an interview?

There are several basic Java interview questions that can appear in an interview. Look at the ones we’ve listed above to get a sense of them.

2. How should I prepare for a Java interview?

You should prepare for a Java interview by learning both the theory and practicing coding. There are several related questions above.

3. What are the advanced Java interview questions?

Advanced Java interview questions can be of many kinds, including both theory and coding-based questions. Check out the list of Java programming questions above to see what they are like.

People are also reading:

  • Best Java Courses
  • Top 10 Java Certifications
  • Best Java Books
  • Best Java Projects
  • Programming Interview Questions
  • Core Java Cheatsheet - Introduction to Programming in Java
  • Difference between Java vs Javascript
  • Top 10 Java Frameworks
  • Best Way to Learn Java
  • Constructor in Java 
  • Prime Number Program in Java

assignment questions on exception handling in java

Simran works at Hackr as a technical writer. The graduate in MS Computer Science from the well known CS hub, aka Silicon Valley, is also an editor of the website. She enjoys writing about any tech topic, including programming, algorithms, cloud, data science, and AI. Traveling, sketching, and gardening are the hobbies that interest her.

Subscribe to our Newsletter for Articles, News, & Jobs.

Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.

In this article

  • Top 48 Networking Interview Questions and Answers in 2024 Computer Networks Career Development Interview Questions
  • Top 20 REST API Interview Questions & Answers [2024] Web Development Career Development Interview Questions
  • How to Extract a Java Substring [with Code Examples] Java

Please login to leave comments

Always be in the loop.

Get news once a week, and don't worry — no spam.

{{ errors }}

{{ message }}

  • Help center
  • We ❤️ Feedback
  • Advertise / Partner
  • Write for us
  • Privacy Policy
  • Cookie Policy
  • Change Privacy Settings
  • Disclosure Policy
  • Terms and Conditions
  • Refund Policy

Disclosure: This page may contain affliate links, meaning when you click the links and make a purchase, we receive a commission.

IMAGES

  1. Java Exception Handling with Examples

    assignment questions on exception handling in java

  2. Java Exception Handling with Examples

    assignment questions on exception handling in java

  3. Exception Handling Interview Question Java

    assignment questions on exception handling in java

  4. Exception Handling In Java Practice Questions

    assignment questions on exception handling in java

  5. Java Exception Handling Example Tutorial

    assignment questions on exception handling in java

  6. Java Exception Handling

    assignment questions on exception handling in java

VIDEO

  1. Fresher Mock Interview Java

  2. 8. Java Variables and Operators

  3. Internship interview questions

  4. Exception in java interview questions and answers part 1 #exceptionhandling #java #interview

  5. Write a java program that...

  6. Write a java program that...

COMMENTS

  1. Java Exception Handling

    It includes try, catch, and finally block, as well as chained exceptions and logging exercises. 1. Write a Java program that throws an exception and catch it using a try-catch block. 2. Write a Java program to create a method that takes an integer as a parameter and throws an exception if the number is odd. 3.

  2. Java Exceptions Interview Questions (+ Answers)

    3. Conclusion. In this article, we've explored some of the questions that are likely to appear in technical interviews for Java developers, regarding exceptions. This is not an exhaustive list, and it should be treated only as the start of further research. We, at Baeldung, wish you success in any upcoming interviews.

  3. 30+ Java Exception Handling Interview Questions And Answers

    30+ Most Asked Java Exception Handling Interview Questions And Answers. 1) What is an exception? Exception is an abnormal condition which occurs during the execution of a program and disrupts normal flow of a program. This exception must be handled properly.

  4. Java Exception Interview Questions and Answers

    Java provides a robust and object-oriented approach to handle exception scenarios known as Java Exception Handling. Sometime back I wrote a long post on Exception Handling in Java and today I am listing some important Java Exceptions Questions with Answers to help you in ... We have to remove the assignment of "e" to a new exception object ...

  5. Java Exception Handling (With Examples)

    3. Java throw and throws keyword. The Java throw keyword is used to explicitly throw a single exception.. When we throw an exception, the flow of the program moves from the try block to the catch block.. Example: Exception handling using Java throw class Main { public static void divideByZero() { // throw an exception throw new ArithmeticException("Trying to divide by 0"); } public static void ...

  6. 35 Java Exception Handling Interview Questions and Answers

    Many interviewers like to test your basic Java skills by asking you about exception handling in Java. And thus, practicing Java exception handling interview questions before your tech interview can help you ace it.. Exception handling ensures that the program's flow does not break when an exception occurs. For example, suppose a program contains many statements, and an exception occurs in the ...

  7. Exception Handling in Java: A Complete Guide with Best and Worst Practices

    Overview. Handling Exceptions in Java is one of the most basic and fundamental things a developer should know by heart. Sadly, this is often overlooked and the importance of exception handling is underestimated - it's as important as the rest of the code.

  8. Java Exception Handling Interview Questions and Answers

    1. try: Enclose the code that might throw an exception within a try block. If an exception occurs within the try block, that exception is handled by an exception handler associated with it. The try block contains at least one catch block or finally block. 2. catch - Java catch block is used to handle the Exception.

  9. Exception Handling in Java

    at Exceptions.getPlayers(Exceptions.java:12) <-- Exception arises in getPlayers() method, on line 12. at Exceptions.main(Exceptions.java:19) <-- getPlayers() is called by main(), on line 19. Copy. Without handling this exception, an otherwise healthy program may stop running altogether! We need to make sure that our code has a plan for when ...

  10. Top 50 Java Exception Handling Interview Questions

    Java Exception Handling Interview Questions test the developer's deep understanding of Java's exception handling mechanisms, such as try-catch blocks, throw and throws keywords, and custom exception creation. Java Exception Handling Interview Questions for Experienced delves into scenarios involving stack traces, exception propagation, and best ...

  11. Java Exception Handling Interview Questions and Answers 2023

    Five keywords manage Java exception handling. These are: try, catch, throw, throws, and finally. We have already seen try, catch, and finally. Let us differentiate and understand the throw and throws keyword. 10.

  12. Java Exception Handling: 20 Best Practices for Error-Free Code

    3.20. Document all exceptions in the application with javadoc. Make it a practice to javadoc all exceptions which a piece of code may throw at runtime. Also, try to include a possible courses of action, the user should follow in case these exceptions occur. That's all I have in my mind for now related to Java exception handling best practices.

  13. Exception Handling in Java (with Real Examples)

    Formally, an exception in Java is "an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.". There are many typical causes for exceptions in Java, including: Loss of network connectivity. Invalid input data.

  14. Exceptions in Java

    In Java, Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program's instructions. Exceptions can be caught and handled by the program. When an exception occurs within a method, it creates an object. This object is called the exception object.

  15. Chapter 5 -- Exception Handling in Java

    Java exception handling is managed via five key words : try, catch, throw, throws, and finally. ... Practice Question. Practice 5.1 public class DivideZero { static int ... System.exit(0); } } } Find out the types of exceptions. Assignment. Q: Is there any way to "get around" the strict restrictions placed on methods by the throws clause? Q ...

  16. The Java Interview Prep Handbook

    Java is well-known for its robustness in Object-Oriented Programming (OOP), and it provides a comprehensive foundation essential for developers at every level. This handbook offers a detailed pathway to help you excel in Java interviews. It focuses on delivering insights and techniques relevant to roles in esteemed big tech companies, ensuring ...

  17. Exception Handling In Java

    in Java Tutorials April 19, 2024 Comments Off. What is Exception Handling In Java - When we work with a program we come up with different kinds of errors like syntactical errors, logical errors, runtime errors, etc. let us try to differentiate these errors with a simple program. Example Program To Differentiate the Errors: 1. 2.

  18. Exception Handling in Java

    Java provides five keywords that are used to handle the exception. The following table describes each. Keyword. Description. try. The "try" keyword is used to specify a block where we should place an exception code. It means we can't use try block alone. The try block must be followed by either catch or finally. catch.

  19. Top Java Exception Handling Interview Questions & Answers (2024

    As of Java 7, the new feature "try-with-resources" helps to autoclose the resources that extend the "AutoCloseable" interface. The close () method will be called when it exits the try-with-resources block. For example, the above code which has a close () method call could be simplified as shown below:

  20. Built-in Exceptions in Java with examples

    Java Interview Questions. Java Interview Questions; ... The above exception occurs whenever while executing static variable assignment and static block if any Exception occurs. 5. ... exception handling is the expected termination of the program. Illustration: Considering a real-life example Suppose books requirement is from Delhi librar ...

  21. Top 80 Java Interview Questions and Answers [2024]

    Two important properties of a Java object are behavior and state. An object is created as soon as the JVM comes across the new keyword. 17. Define classes in Java. A class is a collection of objects of similar data types. Classes are user-defined data types and behave like built-in types of a programming language.

  22. 65 Java Exception Handling Interview Questions for 2024

    Ans: There can be many reasons that might generate an exception in a Java program. Opening a non-existing file in your program. Reading a file from a disk but the file does exist there. Writing data to a disk but the disk is full or unformatted. When the program asks for user input and the user enters invalid data.

  23. Java Exception Handling Assignment

    Java Exception Handling Assignment. Ask Question Asked 10 years, 3 months ago. Modified 3 years, ... So I've recently learned exception handling for Java and I'm still trying to get used to it and all but I feel like I'm missing something. I was doing an assignment for my class and the compiler doesn't like my code. ... Exception Handling ...