Flat 20% & up to 50% off + Free additional Courses. Hurry up!

Top Java Interview Questions And Answers

Here are top 30 objective type sample Java Interview questions and their answers are given just below to them. These sample questions are framed by experts from Intellipaat who trains for Java training to give you an idea of type of questions which may be asked in interview. We have taken full care to give correct answers for all the questions. Do comment your thoughts Happy Job Hunting!

Top Answers to Java Interview Questions

1.Explanations about types of memory areas are allocated by the JVM (Java Virtual Machine)?
There are Five types of memory areas are allocated by the JVM
1. Class Area
2. Heap
3. Stack
4. Program Counter Register
5. Native Method Stack
2.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.
Prepare yourself for the Java Certification with comprehensive Online Java Training Now!
3.How can we restrict inheritance for a class?
We can restrict inheritance for class by following steps.
1. By using final keyword
2. If we make all method final, then we cannot override that.
3. By using private constructors
4. By using Javadoc comment (//)
4.Java doesn’t support multiple inheritance. Why?
Java doesn’t support multiple inheritance. Because we cannot use different methods in one class it creates an ambiguity.
class Intellipaat1
void test()
system.out.println(“test() method”);
}class Intellipaat2
void test()
system.out.println(“test() method”);
}Multiple inheritance
class C extends Intellipaat1, Intellipaat2
}Intellipaat1 and Intellipaat2 test() methods are inheriting to class C
So which test() method C class will take. As Intellipaat1 & Intellipaat2 class test () methods are different, So here we would face ambiguity.

5.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.
6.Define JSON?
Expansion of JSON is “JavaScript Object Notation”, It is a much lighter and readable alternative to XML. It is an independent and easily parse-able in all programming languages. It is primarily used for Communicating between client – server or server -server communication. It is a much lighter and readable alternative to XML.
7.What are the advantages of JSON over XML?
The advantages of JSON over XML are
1. JSON is Lighter and faster than XML
2. Better understandable.
3. Easy to parse and conversion to objects for information consumption.
4. Support multiple data types – JSON support string, number, array, Boolean but XML data are all strings.
8.Name the methods of Object Class?
clone() – This method helps to create and return a copy of the object.
equals() – This method helps to compare
finalize() – Called by the garbage collector on an object
getClass() – It helps to return the runtime class of an object.
hashCode() – Helps to return a hash code value for the object.
toString() – helps to return a string representation of the object.
notify(), notifyAll(), and wait() – It helps to synchronize the activities of independently running threads in a program.
9.Define content negotiation?
If we have visited website to searching the information, we will get the information in different languages and in different formats when a client makes an HTTP request to a server, the client can also specify the media types here. The client can specify what it can accept back from the host and on the basis of availability the host will return to the client. This is known as content negotiation because client and server negotiated on the language and format of the content to be shared.
10.Can we import same package/class two times? Will the JVM load the package twice at runtime?
Yes, we can import the same package/class multiple times. Compiler and JVM are not complaining about it. And the JVM will internally load the class only once no matter how many times we import the same class.
11.Define Abstract class?
1. abstract is a keyword, when we declared with this keyword, the class is called abstract.
2. An abstract class may include an abstract method and also includes n numbers of the concrete method.
3. This class can have public, private, protected or constants and default variables.
4. An abstract class can have concrete and abstract methods.
5. It doesn’t support multiple inheritance, whereas an abstract class does.
12.Describe the Annotations?
It is a form of metadata and it provides data about a program that is not part of the program itself. An annotation has no direct effect on the operation of the code they annotate.
Uses of Annotations
• Information for the compiler — It can be used by the compiler to detect errors or suppress warnings.
• Compile-time and deployment-time processing — some software tools can process annotation information to generate code, XML files, and so forth.
• Runtime processing — few annotations are available to be examined at runtime.
13.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.
14.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);
15.Explain Struts 1 Classes are not Thread Safe whereas Struts 2 classes are thread safe?
Struts 1 actions are a singleton. So all threads operate on the single action object and hence make it thread-unsafe.Struts 2 actions are not a singleton and a new action object copy are created each time a new action request is made and hence it threads safe.
16.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.
17.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.
18.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.
19.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.
20.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.
21.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.
22.What is the difference between transient and volatile variable in Java?
Transient: In Java, it is used to specify the variable is not being serialized. Serialization is a process of saving an object’s state in Java. When we want to persist and the object’s state by default, all instance variables in the object are stored. In some cases, if we want to avoid persisting few variables because we don’t have the necessity to transfer across the network. So, declare those variables as transient. If the variable is confirmed as transient, then it will not be persisted. Transient keyword is used with that instance variable which will not participate in the serialization process. We cannot use static with a transient variable as they are part of the instance variable.Volatile: Volatile keyword is used with only variable in Java and it guarantees that the value of the volatile variable will always be read from main memory and not from Thread’s local cache, it can be static.
23.Why does Map interface not extend the Collection interface in the Java Collections Framework?
The map interface is not compatible with the Collection interface. Because Map requires key as well as value, for example: if we want to add key-value pair so we will use put(Object key , Object value). There are two parameters required to add an element to HashMap object. In Collection interface add(Object o) has only one parameter.
The other reasons are Map supports valueSet, keySet as well as other suitable methods which have just different views from the Collection interface.
24.Mention the uses of Synchronized block
We are using Synchronized block because
• It helps to lock an object for every shared resource.
• The scope of synchronized block is smaller than the method.
25.What are the functions of hashCode() method?
This method returns a hash code value (an integer number).
And also returns the same integer number, if two keys (by calling equals() method) are same.
But in sometimes two hash code numbers can have different or same keys.
26.What is the default size of load factor in hashing based collection?
Default Size = 0.75. The default capacity is computed as initial capacity * load factor.
27.What are the differences between the JSP custom tags & Java beans?
• Custom tags can manipulate JSP content, but beans cannot.
• Composite operations can be reduced to a considerably simpler form with custom tags than with beans.
• Custom tags require reasonably a bit more work to set up than do beans.
• Custom tags are available only in JSP 1.1 and so on, but beans can be used in all JSP 1.x versions
28.Explain Expression Language in JSP?
The expression language is used in JSP to simplify the accessibility of objects and It provides many objects that can be used directly like param, requestScope, sessionScope, applicationScope, request, session etc.
29.Define the implicit object?
JSP implicit objects are those Java objects that the JSP Container makes available to developers in every page. A developer can able to call them directly, without being explicitly declared. JSP Implicit Objects are also known as pre-defined variables. The following objects are considered implicit in a JSP page:
• application
• page
• request
• response
• session
• exception
• out
• config
• pageContext
30.Define a cookie and what are the difference between session and cookie?
A cookie is a small piece of information, this piece of information sends to the browser by a web server. The browser stores the cookies for every Web server in a local file. In a future request or future reference, the browser sends all stored cookies for that detailed Web server.
The difference between cookies and sessions are:
• The session is working, regardless of the settings on the client browser. The client may have selected to disable cookies.
• The session and cookies also differ in storing the amount of information. The HTTP session is able to store any Java object, while a cookie can only store String objects.
31.What is HTTP Tunneling?
HTTP Tunneling is a technique by which, communications performed using various network protocols are encapsulated using the HTTPS protocols. The HTTP protocol, therefore, acts as a wrapper for a channel that the network protocol being tunneled use to communicating. The masking of other protocol requests as HTTP requests is HTTP Tunneling.
32.What is a function of IOC container in spring?
IOC container is responsible to:
• create the instance
• configure the instance, and
• assemble the dependencies
33.What is lazy loading in hibernate?
Lazy loading in hibernate improves the performance. It loads the child objects on demand.
while Hibernate 3, lazy loading is enabled by default, we don’t need to do lazy=”true”. It means not to load the child objects when a parent is loaded.
34.How can we fetch records by spring JdbcTemplate?
. We can fetch records from the database by the query method of JdbcTemplate. There are two interfaces to do this:
1. ResultSetExtractor
2. RowMapper
35.What is the front controller class of Spring MVC?
The Dispatcher Servlet class works as the front controller in Spring MVC.
36.What are the states of an object in hibernate?
The states of an object in hibernate are
1. Transient
2. Persistent
3. Detached
1. Transient: The object is in the transient state if it is just created but has no primary key (identifier) and it is not associated with the session.
2. Persistent: The object is in the persistent state if the session is open, and we just saved the instance in the database or retrieved the instance from the database.
3. Detached: The object is in the detached state if the session is closed. After detached state, the object comes to persistent state if we call lock() or update() method.
37.How to make an immutable class in hibernate?
If we mark a class as mutable=”false”, the class will be treated as an immutable class. The default value of mutable is “true”.
38.What is hash-collision in Hashtable? How was it handled in Java?
In Hashtable , if two different keys have the same hash value then it leads to hash -collision. A bucket of type linked list used to hold the different keys of same hash value.
39.Write a syntax to convert a given Collection to SynchronizedCollection ?
Collections.synchronizedCollection(Collection collectionObj) will convert a given collection to synchronized collection.
40.Write a code to make Collections readOnly?
We can make the Collection readOnly by using the following lines code:
General : Collections.unmodifiableCollection(Collection c)Collections.unmodifiableMap(Map m)
Collections.unmodifiableList(List l)
Collections.unmodifiableSet(Set s)
41.What is meant by binding in RMI?
Binding is the process of associating or registering a name for a remote object, which can be used as a further, in order to look up that remote object. A remote object can be associated with a name using the bind / rebind methods of the Naming class.
42.What are latest features introduced with Java 8?
The below latest features are introduced in Java 8. Lambda Expressions, Interface Default and Static Methods, Method Reference, Parameters Name, Optional Streams, Concurrency.
43.Name few Java 8 annotations?
1. @Functional Interface annotation
2. @Repeatable annotation,
@Functional Interface annotation: It was introduced in Java SE 8, indicates that the type declaration is intended to be a functional interface, as defined by the Java Language Specification.@Repeatable annotation: introduced in Java SE 8, indicates that the marked annotation can be applied many times to the same declaration or type use.
44.Distinguish between a predicate and a function?
A predicate takes one argument and returns a Boolean value.
A function takes one argument and returns an object.
Both are useful for evaluating lambda expressions.
45.Write a code to sort a list of strings using Java 8 lambda expression?
. private void sortUsingJava8(List names){
Collections.sort(names, (p1, p2) -> p1.compareTo(p2));
46.What is Nashorn in Java8?
With Java 8, Nashorn, a much-improved javascript engine is introduced and Nashron replaced the existing Rhino. It provides 2 to 10 times better performance, as it directly compiles the code in memory and passes the bytecode to JVM. Nashorn uses invoke the dynamic feature, introduced in Java 7 to improve performance.
47.Define a StringJoiner and write a sample code?
StringJoiner is an util method to construct a string with the desired delimiter.
Sample CodeStringJoiner strJoiner = new StringJoiner(“.”);
48.Can you execute javascript code from Java 8 code base?
Yes! We can execute javascript code from Java8 code based by using ScriptEngineManager, We called JavaScript code and interpreted in Java.
This blog will help you get a better understanding of Mobile Technology for Android and iOS using Java !

"17 Responses on Top Java Interview Questions And Answers"

  1. Prem says:

    Thanks for sharing the valuable info. But I have one doubt. I want to re-reach and use an object once it has been garbage collected. How it’s possible?

    • Moderator says:

      Once an object has been destroyed by garbage collector, it no longer exists on the heap and it can’t be accessed again. There is no way to reference it again.

  2. Sandeep says:

    Pleasant update for Java interviewee!

  3. Patel says:

    Big list, almost cover all topics required for Java interviews. Good Job

  4. John says:

    I have multiple constructors defined in a class. Is it possible to call a constructor from another constructor’s body?

    • Moderator says:

      If a class has multiple constructors, it’s possible to call one constructor from the body of another one using this().

  5. Kiran says:

    Surely it will help for fresher’s as well as experienced candidates. Dear author please keep it up. Thanks.

  6. Garry says:

    Great list of questions and short answers. This helps revising concepts quickly before interview. Appreciate your efforts.

  7. Sonal says:

    Questions based on OOPS, Multithreading, Exception handling, Java fundamentals and sometimes Unit Testing are most common.

  8. Nilam says:

    This is an excellent collection. Can I request you to add more and tough Java questions please.

  9. Anonymous says:

    effective collection of interview ques…..grt.

  10. Kenu says:

    Thanks for sharing very nice descriptive Interview questions and answers.

  11. Suresh says:

    Thanks for sharing the great IQA, I refreshed my java knowledge once again.

  12. Muskaan says:

    Thank you very much for sharing such good collection of questions on wide variety of topics of java

  13. Sneha Bansal says:

    Great collection of interview questions..very helpful for my project viva

  14. Hitesh says:

    I am also a Java Programmer from india .Your questions are very good for those student or person wants to start career as a java developer.Nice and thanks..

  15. Mehul says:

    I am really thankful to the author for sharing such a great collection of Interview Questions and Answers. Tomorrow I have an interview round. So this guide would be really helpful.

Leave a Message

Your email address will not be published.

Training in Cities

Bangalore, Hyderabad, Chennai, Delhi, Kolkata, UK, London, Chicago, San Francisco, Dallas, Washington, New York, Orlando, Boston

100% Secure Payments. All major credit & debit cards accepted Or Pay by Paypal.


Sales Offer

  • To avail this offer, enroll before 25th October 2016.
  • This offer cannot be combined with any other offer.
  • This offer is valid on selected courses only.
  • Please use coupon codes mentioned below to avail the offer
DW offer

Sign Up or Login to view the Free Top Java Interview Questions And Answers.