1. Why Java is platform independent?
Platform independent practically means “write once run anywhere”. Java is called so because of its byte codes which can run on any system irrespective of its underlying operating system.

2. Why java is not 100% Object-oriented?
Java is not 100% Object-oriented because it makes use of eight primitive datatypes such as boolean, byte, char, int, float, double, long, short which are not objects.

3. What are wrapper classes?
Wrapper classes converts the java primitives into the reference types (objects). Every primitive data type has a class dedicated to it. These are known as wrapper classes because they “wrap” the primitive data type into an object of that class. Refer to the below image which displays different primitive type, wrapper class and constructor argument. 

4. What are constructors in Java?
In Java, constructor refers to a block of code which is used to initialize an object. It must have the same name as that of the class. Also, it has no return type and it is automatically called when an object is created.

5. What is singleton class and how can we make a class singleton?
Singleton class is a class whose only one instance can be created at any given time, in one JVM. A class can be made singleton by making its constructor private.

6. What is the difference between equals() and == ?
Equals() method is defined in Object class in Java and used for checking equality of two objects defined by business logic.
“==” or equality operator in Java is a binary operator provided by Java programming language and used to compare primitives and objects. public boolean equals(Object o) is the method provided by the Object class. The default implementation uses == operator to compare two objects. For example: method can be overridden like String class. equals() method is used to compare the values of two objects.

7. What is Polymorphism?
Polymorphism is briefly described as “one interface, many implementations”. Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts – specifically, to allow an entity such as a variable, a function, or an object to have more than one form. 

8. What is association?
Association is a relationship where all object have their own lifecycle and there is no owner. Let’s take an example of Teacher and Student. Multiple students can associate with a single teacher and a single student can associate with multiple teachers but there is no ownership between the objects and both have their own lifecycle. These relationship can be one to one, One to many, many to one and many to many.

9. What is a servlet?
Java Servlet is server side technologies to extend the capability of web servers by providing support for dynamic response and data persistence.
The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing our own servlets.
All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle methods. When implementing a generic service, we can extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet() and doPost(), for handling HTTP-specific services.
Most of the times, web applications are accessed using HTTP protocol and thats why we mostly extend HttpServlet class. Servlet API hierarchy is shown in below image.

10. What is Request Dispatcher?
RequestDispatcher interface is used to forward the request to another resource that can be HTML, JSP or another servlet in same application. We can also use this to include the content of another resource to the response.

11. How does cookies work in Servlets?
Cookies are text data sent by server to the client and it gets saved at the client local machine.
Servlet API provides cookies support through javax.servlet.http.Cookie class that implements Serializable and Cloneable interfaces.
HttpServletRequest getCookies() method is provided to get the array of Cookies from request, since there is no point of adding Cookie to request, there are no methods to set or add cookie to request.
Similarly HttpServletResponse addCookie(Cookie c) method is provided to attach cookie in response header, there are no getter methods for cookie.

12. What are the different methods of session management in servlets?
Session is a conversational state between client and server and it can consists of multiple request and response between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response.

Also Read:- Top 10 Java Interview Question Answers.

13. What is the role of JDBC DriverManager class?
The DriverManager class manages the registered drivers. It can be used to register and unregister drivers. It provides factory method that returns the instance of Connection.

14. What is JDBC Connection interface?
The Connection interface maintains a session with the database. It can be used for transaction management. It provides factory methods that returns the instance of Statement, PreparedStatement, CallableStatement and DatabaseMetaData.

15. What is the purpose of JDBC ResultSet interface?
The ResultSet object represents a row of a table. It can be used to change the cursor pointer and get the information from the database.

16. What is JDBC ResultSetMetaData interface?
The ResultSetMetaData interface returns the information of table such as total number of columns, column name, column type etc.

17. What is JDBC DatabaseMetaData interface?
The DatabaseMetaData interface returns the information of the database such as username, driver name, driver version, number of tables, number of views etc.

18. What do you mean by batch processing in JDBC?
Batch processing helps you to group related SQL statements into a batch and execute them instead of executing a single query. By using batch processing technique in JDBC, you can execute multiple queries which makes the performance faster.

19. What is a Spring?
Wikipedia defines the Spring framework as “an application framework and inversion of control container for the Java platform. The framework’s core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform.” Spring is essentially a lightweight, integrated framework that can be used for developing enterprise applications in java.

20. Name the different modules of the Spring framework.
Some of the important Spring Framework modules are:

Spring Context – for dependency injection.
Spring AOP – for aspect oriented programming.
Spring DAO – for database operations using DAO pattern
Spring JDBC – for JDBC and DataSource support.
Spring ORM – for ORM tools support such as Hibernate
Spring Web Module – for creating web applications.
Spring MVC – Model-View-Controller implementation for creating web applications, web services etc.

21. Explain Bean in Spring and List the different Scopes of Spring bean.
Beans are objects that form the backbone of a Spring application. They are managed by the Spring IoC container. In other words, a bean is an object that is instantiated, assembled, and managed by a Spring IoC container.

22. Explain the role of DispatcherServlet and ContextLoaderListener.
DispatcherServlet is basically the front controller in the Spring MVC application as it loads the spring bean configuration file and initializes all the beans that have been configured. If annotations are enabled, it also scans the packages to configure any bean annotated with @Component, @Controller, @Repository or @Service annotations.

23. 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.

24. What are the important benefits of using Hibernate Framework?
Some of the important benefits of using hibernate framework are:

Hibernate eliminates all the boiler-plate code that comes with JDBC and takes care of managing resources, so we can focus on business logic.
Hibernate framework provides support for XML as well as JPA annotations, that makes our code implementation independent.
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.
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.
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.
Hibernate supports lazy initialization using proxy objects and perform actual database queries only when it’s required.
Hibernate cache helps us in getting better performance.
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.

Also Read:- Top 20 Java Interview Questions and Answers

25. What are the advantages of Hibernate over JDBC?
Some of the important advantages of Hibernate framework over JDBC are:

Hibernate removes a lot of boiler-plate code that comes with JDBC API, the code looks more cleaner and readable.
Hibernate supports inheritance, associations and collections. These features are not present with JDBC API.
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. 
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 throw JDBCException 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.
Hibernate Query Language (HQL) is more object oriented and close to java programming language. For JDBC, we need to write native sql queries.
Hibernate supports caching that is better for performance, JDBC queries are not cached hence performance is low.
Hibernate provide option through which we can create database tables too, for JDBC tables must exist in the database.
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.

26. How to disable caching on back button of the browser?
response.setHeader (“Expires”, “0”);                    //prevents caching at the proxy server

27. How to disable session in JSP?
<%@ page session=“false” %> 

28. How is JSP better than Servlet technology?
JSP is a technology on the server’s side to make content generation simple. They are document centric, whereas servlets are programs. A Java server page can contain fragments of Java program, which execute and instantiate Java classes. However, they occur inside HTML template file. It provides the framework for development of a Web Application.

29. Why should we not configure JSP standard tags in web.xml?

We don’t need to configure JSP standard tags in web.xml because when container loads the web application and find TLD files, it automatically configures them to be used directly in the application JSP pages. We just need to include it in the JSP page using taglib directive.

In case you are facing any challenges with these java interview questions, please comment your problems in the section below.

30. 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.

31. 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.

32. 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.

String getMessage() – This method returns the message String of Throwable and the message can be provided while creating the exception through it’s constructor.
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.
Synchronized Throwable getCause() – This method returns the cause of the exception or null id the cause is unknown.
String toString() – This method returns the information about Throwable in String format, the returned String contains the name of Throwable class and localized message.
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.

33. What is a finally block? Is there a case when finally will not execute?
Finally block is a block which always executes 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.

34. 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.

35. Can you differentiate between J2SDK 1.5 and J2SDK 5.0?
There is really no difference between J2SDK 1.5 and J2SDK 5.0. The versions have been rebranded by Sun Microsystems.

36. Is it possible to import same package or class twice? Will the JVM load the package twice at runtime?
It is possible to import the same package or class more than once. It will not have any effect on the compiler or JVM. The JVM will load the class more than once, irrespective of the number of times you import the same class.

Also Read:- Top 30 Java Interview Questions and Answers

37. How does the substring() method of String class create memory leaks?
The substring method can build a new String object with reference to the while char array, to avoid copying it. Thus, you can inadvertently keep a reference to a very big character array with just one character string.

38. Why is Char array preferred over String to store a password?
String is immutable in Java and stored in the String pool. Once it is created it stays in the pool until the garbage is created making the password available in the memory. It is a security risk because anyone who has access to the memory dump can find the password as clear text.

39. What Is Multi-Threading?
Multi-threading is a programming concept used to run multiple tasks in a concurrent manner within a single program.

40. What Is the Difference Between Static and Dynamic Loading?
Static class loading involves the creation of objects and instances using new keywords, and dynamic class loading is done when the name of the class is not known at compile time.

41. Define Class in Java.
In Java, a class is a template used to create objects and define the data type. It acts as a building block for Java language-oriented systems.

42. When and by Whom was Java Developed?
Java was developed by James Gosling in Sun Microsystem in 1995.

43. What Do JDK, JRE, and JVM Stand for?
JVM stands for Java Virtual Machine
JRE stands for Java Runtime Environment
JDK stands for Java Development Kit

44. Does Java Use Pointers?
No. Java doesn’t use pointers. It has a tough security. Instead of pointers, references are used in Java as they are safer and more secure when compared to a pointer.

45. What Are the Functions of JVM and JRE?
JVM provides a runtime environment for Java Byte Codes to be executed. JRE includes sets of files required by JVM during runtime.

46. What Is a Package?
A package is a collection of related classes and interfaces.

47. What's the Base Class of all Exception Classes?
Java.lang.Throwable is the superclass of all exception classes, and all exception classes are derived from this base class.

48. State Two Differences Between an Inner Class and a Subclass
While Inner classes are in the same file, subclasses can be in another file. With that in mind, while subclasses have the methods of their parent class, inner classes get the methods they want.

Also Read:- Top 40 Java Interview Questions and Answers

49. Define JSON.
JSON is an acronym for JavaScript Object Notation. It uses JavaScript syntax, and the format is text only.

50. How Are Destructors Defined in Java?
Since Java has its own garbage collection, no destructors are required to be defined.       Destruction of objects is automatically carried by the garbage collection mechanism.

51. What Is an Anonymous Class?
The class defined without a name in a single line of code using new keyword is known as an anonymous class.

52. Name the Most Important Feature of Java
Java is a platform independent language.

53. What Is a JVM?
JVM is the Java Virtual Machine, which is a runtime environment for compiled Java class files.

54. Can a Dead Thread Be Started Again?
No, a thread that is in the dead state can't be started again.

55. Are Arrays of Primitive Data Types?
No. In Java, Arrays are objects.

56. What Are Constructors in Java?
In Java, the constructor is a block of code used to initialize an object.

57. Explain Garbage Collection in Java.
In Java, when an object is no longer used or referenced, garbage collection is called and the object is destroyed automatically.

58. What's the Difference Between Stack and Queue?
The difference between a stack and a queue is that the stack is based on the Last in First out (LIFO) principle, and a queue is based on FIFO (First In, First Out) principle.

59. What is immutable object? Can you write immutable object?Immutable classes are Java classes whose objects can not be modified once created. Any modification in Immutable object result in new object. For example is String is immutable in Java. Mostly Immutable are also final in Java, in order to prevent sub class from overriding methods in Java which can compromise Immutability. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.

60. Write code to find the First non repeated character in the String  ?
Another good Java interview question, This question is mainly asked by Amazon and equivalent companies.

Also Read:- Top 50 Java Interview Questions and Answers

61. What is difference between StringBuffer and StringBuilder in Java ?
Classic Java questions which some people thing tricky and some consider very easy. StringBuilder in Java is introduced in Java 5 and only difference between both of them is that Stringbuffer methods are synchronized while StringBuilder is non synchronized. See StringBuilder vs StringBuffer for more differences.

62. How do you handle error condition  while writing stored procedure or accessing stored procedure from java?
This is one of the tough Java interview question and its open for all, my friend didn't know the answer so he didn't mind telling me. my take is that stored procedure should return error code if some operation fails but if stored procedure itself fail than catching SQLException is only choice.

63. What is the difference between factory and abstract factory pattern?
Abstract Factory provides one more level of abstraction. Consider different factories each extended from an Abstract Factory and responsible for creation of different hierarchies of objects based on the type of factory. E.g. AbstractFactory extended by AutomobileFactory, UserFactory, RoleFactory etc. Each individual factory would be responsible for creation of objects in that genre.

64. When do you override hashcode and equals() ?
Whenever necessary especially if you want to do equality check or want to use your object as key in HashMap.

65. Is it better to synchronize critical section of getInstance() method or whole getInstance() method ?
Answer is critical section because if we lock whole method than every time some one call this method will have to wait even though we are not creating any object)

66. What is the difference when String is gets created using literal or new() operator ?
When we create string with new() its created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.

67. What’s wrong using HashMap in multithreaded environment? When get() method go to infinite loop ?
Another good question. His answer was during concurrent access and re-sizing.

68. Does not overriding hashcode() method has any performance implication ?
This is a good question and open to all , as per my knowledge a poor hashcode function will result in frequent collision in HashMap which eventually increase time for adding an object into Hash Map.

69. What will happen if you call return statement or System.exit on try or catch block ? will finally block execute?
This is a very popular tricky Java question and its tricky because many programmer think that finally block always executed. This question challenge that concept by putting return statement in try or catch block or calling System.exit from try or catch block. Answer of this tricky question in Java is that finally block will execute even if you put return statement in try block or catch block but finally block won't run if you call System.exit form try or catch.

70. Can you override private or static method in Java ?
Another popular Java tricky question, As I said method overriding is a good topic to ask trick questions in Java.  Anyway, you can not override private or static method in Java, if you create similar method with same return type and same method arguments that's called method hiding. 

71. If a method throws NullPointerException in super class, can we override it with a method which throws RuntimeException?
One more tricky Java questions from overloading and overriding concept. Answer is you can very well throw super class of RuntimeException in overridden method but you can not do same if its checked Exception. 

72. What will happen if we put a key object in a HashMap which is already there ?
This tricky Java questions is part of How HashMap works in Java, which is also a popular topic to create confusing and tricky question in Java. well if you put the same key again than it will replace the old mapping because HashMap doesn't allow duplicate keys. 

Also Read:- Top 60 Java Interview Questions and Answers

73. How do you ensure that N thread can access N resources without deadlock
If you are not well versed in writing multi-threading code then this is real tricky question for you. This Java question can be tricky even for experienced and senior programmer, who are not really exposed to deadlock and race conditions. Key point here is order, if you acquire resources in a particular order and release resources in reverse order you can prevent deadlock. 

74. What is difference between CyclicBarrier and CountDownLatch in Java
Relatively newer Java tricky question, only been introduced form Java 5. Main difference between both of them is that you can reuse CyclicBarrier even if Barrier is broken but you can not reuse CountDownLatch in Java. See CyclicBarrier vs CountDownLatch in Java for more differences.

75. Can you access non static variable in static context?
Another tricky Java question from Java fundamentals. No you can not access static variable in non static context in Java. Read why you can not access non-static variable from static method to learn more about this tricky Java questions.

76. What is the difference between sleep() and wait() method?
sleep() does not release the lock while wait method release the lock. sleep() method is present in java.lang.Thread class while wait() method  is present in java.lang.Object class.

77. What do you mean by Object?
An object consists of methods and class which depict its state and perform operations. A java program contains a lot of objects instructing each other their jobs. This concept is a part of core java.

78. Compare Overloading and Overriding.
Overloading refers to the case of having two methods of same name but different properties, but overriding occurs when there are two methods of same name and properties, but one is in child class and one is in parent class.

79. Explain method overloading.
When a Java program contains more than one methods with the same name but different properties, then it is called method overloading.

80. Can we execute any code, even before the main method? Explain?
Yes, We can execute any code, even before the main method. We are using a static block of code in the class when creating the objects at load time of class. Any statements within this static block of code will get executed one time while loading the class, even before the creation of objects in the main method.

81. Are constructors inherited? Can a subclass call the parent's class constructor?
We cannot inherit a constructor. We create an instance of a subclass using a constructor of one of its superclass. Because override the superclass constructor is not our wish so that, we override a superclass constructor, then we destroy the encapsulation abilities of the language.

82. Can we import same package/class two times? Will the JVM load the package twice at runtime?
A package or class can be inherited multiple times in a program code. JVM and compiler will not create any issue. Moreover JVM automatically loads the class internally once regardless of times it is called in the program.

Also Read:- Top 70 Java Interview Questions and Answers

83. Java doesn't use pointers. Why?
Pointers are susceptible and slight carelessness in their use may result in memory problems and hence Java basically manages their use.

84. Distinguish between static loading and dynamic class loading?
Static loading – Classes are loaded statically with operator “new”.Dynamic class loading – It is a technique for programmatically invoking the functions of a class loader at run time. The syntax isClass.forName (Test className);

85. Define JAXP & JAXB?
JAXP: – Stands for Java API for XML Processing. This provides a common interface for creating and using DOM, SAX, and XSLT APIs in Java regardless of which vendor’s implementation is actually being used.
JAXB: – It Stands for Java API for XML Binding. This standard defines a system for a script out Java objects as XML and for creating Java objects from XML structures.

86. Define an enumeration?
Usually, we called enumeration as an enum. An enumeration is an interface containing methods for accessing the original data structure from which the enumeration is obtained. It allows sequential access to all the elements stored in the collection.

87. How can we find the actual size of an object on the heap?
In Java, there is no way to find out the actual size of an object on the heap.

88. Which API is provided by Java for operations on a set of objects?
Java provides a Collection API which provides many useful methods which can be applied to a set of objects. Some of the important classes provided by Collection API include ArrayList, HashMap, TreeSet, and TreeMap.

89. What’s the base class of all exception classes?
Java.Lang.throwable – It is the super class of all exception classes and all exception classes are derived from this base class.

90. Why we used Vector class?
The Vector class provides the ability to execute a growable array of objects. Vector proves to be very useful if you don’t know the size of the array in advance, or we need one that can change sizes over the lifetime of a program.

Also Read:- 10 Steps to Become an Outstanding Java Developer

Follow Knowledge Guru on Twitter, Facebook, LinkedIn, RedditMix, Pinterestbe updated with latest news, Stay in the know with what's happening in the tech world. Get the best of news stories and information about “Innovation & Tech, Business, Startups, Latest News, Photography and trending”. Subscribe to Knowledge Guru Newsletters. For more details email us at knowledgeguru2019@gmail.com