Top 75 Java Interview Questions You Must Prepare In 2018

Exception and Thread Java Interview Questions

Q1. What is difference between Error and Exception?

An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors you can not repair them at runtime.Though error can be caught in catch block but the execution of application will come to a halt and is not recoverable.

While exceptions are conditions that occur because of bad input or human error etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.

Q2. How can you handle Java exceptions?

There are five keywords used to handle exceptions in java: 

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

Q3. What are the differences between Checked Exception and Unchecked Exception?

Checked Exception

  • The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions. 
  • Checked exceptions are checked at compile-time.
  • Example: IOException, SQLException etc.

Unchecked Exception

  • The classes that extend RuntimeException are known as unchecked exceptions. 
  • Unchecked exceptions are not checked at compile-time.
  • Example: ArithmeticException, NullPointerException etc.

Q4. What purpose does the keywords final, finally, and finalize fulfill? 

Final:

Final is used to apply restrictions on class, method and variable. Final class can’t be inherited, final method can’t be overridden and final variable value can’t be changed. Let’s take a look at the example below to understand it better.

1
2
3
4
5
6
class FinalVarExample {
public static void main( String args[])
{
final int a=10;   // Final variable
a=50;             //Error as value can't be changed
}

Finally

Finally is used to place important code, it will be executed whether exception is handled or not. Let’s take a look at the example below to understand it better.

1
2
3
4
5
6
7
8
9
10
11
12
class FinallyExample {
public static void main(String args[]){
try {
int x=100;
}
catch(Exception e) {
System.out.println(e);
}
finally {
System.out.println("finally block is executing");}
}}
}

Finalize

Finalize is used to perform clean up processing just before object is garbage collected. Let’s take a look at the example below to understand it better.

1
2
3
4
5
6
7
8
9
10
11
12
13
class FinalizeExample {
public void finalize() {
System.out.println("Finalize is called");
}
public static void main(String args[])
{
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1= NULL;
f2=NULL;
System.gc();
}
}

 Q5. What are the differences between throw and throws? 

 

 1 Throw:
 2 
 3 ...
 4 void myMethod() {
 5    try {
 6       //throwing arithmetic exception using throw
 7       throw new ArithmeticException("Something went wrong!!");
 8    } 
 9    catch (Exception exp) {
10       System.out.println("Error: "+exp.getMessage());
11    }
12 }
13 ...
14 Throws:
15 
16 ...
17 //Declaring arithmetic exception using throws
18 void sample() throws ArithmeticException{
19    //Statements
20 }
21 ...

 

throw keyword throws keyword
Throw is used to explicitly throw an exception. Throws is used to declare an exception.
Checked exceptions can not be propagated with throw only. Checked exception can be propagated with throws.
Throw is followed by an instance. Throws is followed by class.
Throw is used within the method. Throws is used with the method signature.
You cannot throw multiple exception You can declare multiple exception e.g. public void method()throws IOException,SQLException.

Q6. What is exception hierarchy in java?

The hierarchy is as follows:

Throwable is a parent class of all Exception classes. There are two types of Exceptions: Checked exceptions and UncheckedExceptions or RunTimeExceptions. Both type of exceptions extends Exception class whereas errors are further classified into Virtual Machine error and Assertion error.

ExceptionHierarchy - Java Interview Questions - Edureka

Q7. How to create a custom Exception?

To create you own exception extend the Exception class or any of its subclasses.

  • class New1Exception extends Exception { }               // this will create Checked Exception
  • class NewException extends IOExcpetion { }             // this will create Checked exception
  • class NewException extends NullPonterExcpetion { }  // this will create UnChecked exception

Q8. What are the important methods of Java Exception Class?

Exception and all of it’s subclasses doesn’t provide any specific methods and all of the methods are defined in the base class Throwable.

  1. String getMessage() – This method returns the message String of Throwable and the message can be provided while creating the exception through it’s constructor.
  2. String getLocalizedMessage() – This method is provided so that subclasses can override it to provide locale specific message to the calling program. Throwable class implementation of this method simply use getMessage() method to return the exception message.
  3. Synchronized Throwable getCause() – This method returns the cause of the exception or null id the cause is unknown.
  4. String toString() – This method returns the information about Throwable in String format, the returned String contains the name of Throwable class and localized message.
  5. void printStackTrace() – This method prints the stack trace information to the standard error stream, this method is overloaded and we can pass PrintStream or PrintWriter as argument to write the stack trace information to the file or stream.

Q9. What are the differences between processes and threads?

  Process Thread
Definition An executing instance of a program is called a process. A thread is a subset of the process.
Communication Processes must use inter-process communication to communicate with sibling processes. Threads can directly communicate with other threads of its process.
Control Processes can only exercise control over child processes. Threads can exercise considerable control over threads of the same process.
Changes Any change in the parent process does not affect child processes. Any change in the main thread may affect the behavior of the other threads of the process.
Memory Run in separate memory spaces. Run in shared memory spaces.
Controlled by Process is controlled by the operating system. Threads are controlled by programmer in a program.
Dependence Processes are independent. Threads are dependent.

Q10. What is a finally block? Is there a case when finally will not execute?

Finally block is a block which always execute a set of statements. It is always associated with a try block regardless of any exception that occurs or not. 
Yes, finally will not be executed if the program exits either by calling System.exit() or by causing a fatal error that causes the process to abort.

Q11. What is synchronization?

Synchronization refers to multi-threading. A synchronized block of code can be executed by only one thread at a time. As Java supports execution of multiple threads, two or more threads may access the same fields or objects. Synchronization is a process which keeps all concurrent threads in execution to be in sync. Synchronization avoids memory consistency errors caused due to inconsistent view of shared memory. When a method is declared as synchronized the thread holds the monitor for that method’s object. If another thread is executing the synchronized method the thread is blocked until that thread releases the monitor.

Synchronization - Java Interview Questions - Edureka

 Q12. Can we write multiple catch blocks under single try block? 

Yes we can have multiple catch blocks under single try block but the approach should be from specific to general. Let’s understand this with a programmatic example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Example {
public static void main(String args[]) {
try {
int a[]= new int[10];
a[10]= 10/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic exception in first catch block");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out of bounds in second catch block");
}
catch(Exception e)
{
System.out.println("Any exception in third catch block");
}
}

Q13. What are the important methods of Java Exception Class?

Methods are defined in the base class Throwable. Some of the important methods of Java exception class are stated below. 

  1. String getMessage() – This method returns the message String about the exception . The message can be provided through its constructor.
  2. public StackTraceElement[] getStackTrace() – This method returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack whereas the last element in the array represents the method at the bottom of the call stack.
  3. Synchronized Throwable getCause() – This method returns the cause of the exception or null id as represented by a Throwable object.

  4. String toString() – This method returns the information in String format. The returned String contains the name of Throwable class and localized message.
  5. void printStackTrace() – This method prints the stack trace information to the standard error stream. 

Hibernate Interview Questions

Q1. What is Hibernate Framework?

Object-relational mapping or ORM is the programming technique to map application domain model objects to the relational database tables. Hibernate is java based ORM tool that provides framework for mapping application domain objects to the relational database tables and vice versa.

Hibernate provides reference implementation of Java Persistence API, that makes it a great choice as ORM tool with benefits of loose coupling. We can use Hibernate persistence API for CRUD operations. Hibernate framework provide option to map plain old java objects to traditional database tables with the use of JPA annotations as well as XML based configuration.

Similarly hibernate configurations are flexible and can be done from XML configuration file as well as programmatically.

Q2. What are the important benefits of using Hibernate Framework?

Some of the important benefits of using hibernate framework are:

  1. Hibernate eliminates all the boiler-plate code that comes with JDBC and takes care of managing resources, so we can focus on business logic.
  2. Hibernate framework provides support for XML as well as JPA annotations, that makes our code implementation independent.
  3. Hibernate provides a powerful query language (HQL) that is similar to SQL. However, HQL is fully object-oriented and understands concepts like inheritance, polymorphism and association.
  4. Hibernate is an open source project from Red Hat Community and used worldwide. This makes it a better choice than others because learning curve is small and there are tons of online documentations and help is easily available in forums.
  5. Hibernate is easy to integrate with other Java EE frameworks, it’s so popular that Spring Framework provides built-in support for integrating hibernate with Spring applications.
  6. Hibernate supports lazy initialization using proxy objects and perform actual database queries only when it’s required.
  7. Hibernate cache helps us in getting better performance.
  8. For database vendor specific feature, hibernate is suitable because we can also execute native sql queries.

Overall hibernate is the best choice in current market for ORM tool, it contains all the features that you will ever need in an ORM tool.

Q3. Explain Hibernate architecture?

HibernateArchitecture - Java Interview Questions - Edureka

Q4 What are the differences between get and load methods?

The differences between get() and load() methods are given below.

No. get() load()
 1)  Returns null if object is not found. Throws ObjectNotFoundException if object is not found.
 2)  get() method always hit the database.  load() method doesn’t hit the database.
 3)  It returns real object not proxy.  It returns proxy object.
 4) It should be used if you are not sure about the existence of instance. It should be used if you are sure that instance exists.

Q5 What are the advantages of Hibernate over JDBC?

Some of the important advantages of Hibernate framework over JDBC are:

  1. Hibernate removes a lot of boiler-plate code that comes with JDBC API, the code looks more cleaner and readable.
  2. Hibernate supports inheritance, associations and collections. These features are not present with JDBC API.
  3. Hibernate implicitly provides transaction management, in fact most of the queries can’t be executed outside transaction. In JDBC API, we need to write code for transaction management using commit and rollback. 
  4. JDBC API throws SQLException that is a checked exception, so we need to write a lot of try-catch block code. Most of the times it’s redundant in every JDBC call and used for transaction management. Hibernate wraps JDBC exceptions and throwJDBCException or HibernateException un-checked exception, so we don’t need to write code to handle it. Hibernate built-in transaction management removes the usage of try-catch blocks.
  5. Hibernate Query Language (HQL) is more object oriented and close to java programming language. For JDBC, we need to write native sql queries.
  6. Hibernate supports caching that is better for performance, JDBC queries are not cached hence performance is low.
  7. Hibernate provide option through which we can create database tables too, for JDBC tables must exist in the database.
  8. Hibernate configuration helps us in using JDBC like connection as well as JNDI DataSource for connection pool. This is very important feature in enterprise application and completely missing in JDBC API.

  1. Hibernate supports JPA annotations, so code is independent of implementation and easily replaceable with other ORM tools. JDBC code is very tightly coupled with the application.

猜你喜欢

转载自www.cnblogs.com/vicky-project/p/9314188.html
今日推荐