Top Answers to Java Interview Questions

1. What do you understand by Java?

  • Java is an object-oriented computer language.
  • It is a high-level programming language developed by James Gosling in Sun Microsystems in the year 1995.
  • Java is a fast, secure, and reliable language used for many games, devices, and applications.

Go through this Java Tutorial to get a better understanding of the concept!

2. Compare between Java and Python.

CriteriaJavaPython
Ease of useGoodExcellent
Speed of codingAverageExcellent
Data typesStatic typedDynamically typed
Data Science and Machine Learning applicationsAverageExcellent

3. Outline the major Java features.

  • Object-oriented: Java is based on object-oriented programming where the class and methods describe the state and behavior of an object.
  • Portable: A Java program gets converted into Java bytecodes that can be executed on any platform without any dependency.
  • Platform independent: Java works on the ‘write once, run anywhere’ principle as it supports multiple platforms like Windows, Linux, Mac, Sun Solaris, etc.
  • Robust: Java has strong memory management as there are no pointer allocations. It has an automatic garbage collection that prohibits memory leaks.
  • Interpreted: As mentioned, Java compiler converts the codes into Java bytecodes which are then interpreted and executed by Java Interpreter.

Become a master of Java by enrolling in this online Java Course!

CTA

Watch this Java Interview Questions video:

Top Java Interview Questions and Answers Want to Learn Java? Click Here

Learn for free ! Subscribe to our youtube Channel.

4. What do you mean by an object?

An object consists of methods and classes that depict its state and perform operations. A Java program contains a lot of objects instructing each other their jobs. This concept is part of core Java.

5. What is a class in Java?

Java encapsulates codes in various classes that define new data types. These new data types are used to create objects.

6. Differentiate between JDK, JRE, and JVM.

  • JVM stands for Java Virtual Machine which provides the runtime environment for Java bytecodes to be executed.
  • JRE (Java Runtime Environment) includes the sets of files required by JVM during runtime.
  • JDK (Java Development Kit) consists of JRE along with the development tools required to write and execute a program.

Get a clear idea of why to get certified in Java!

7. Define inheritance.

Java includes the feature of inheritance which is an object-oriented programming concept. Inheritance lets a derived class inherit the methods of a base class.

8. Explain method overloading.

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

9. Compare overloading with overriding.

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

Read this tutorial to get a clear understanding of inheritance in Java!

10. Explain the creation of a thread-safe singleton in Java using double-checked locking.

Singleton is created with the double-checked locking as before Java 5 acts as a broker and it’s been possible to have multiple instances of singleton when multiple threads create an instance of the singleton at the same time. Java 5 made it easy to create thread-safe singleton using Enum. Using a volatile variable is essential for the same.

11. Distinguish between StringBuffer and StringBuilder in Java programming.

StringBufferStringBuilder
StringBuffer methods are synchronized.StringBuilder is non-synchronized.
The storage area is heap and modified easily.Storage is heap and can be modified.
StringBuffer is thread-safe.StringBuilder is fast as it is not thread-safe.
The performance is very slow.The performance is very fast.

Go through this tutorial to get a better understanding of Java String!

12. Differentiate between an ArrayList and a Vector.

ArrayListVector
An ArrayList is not synchronized.A vector is synchronized.
An ArrayList is fast.A vector is slow as it is thread-safe.
If an element is inserted into an ArrayList, it increases its array size by 50 percent.A vector defaults to doubling the size of its array.
An ArrayList does not define the increment size.A vector defines the increment size.
An ArrayList can only use Iterator for traversing.Except for hashtable, a vector is the only other class that uses both Enumeration and Iterator.

 

13. Mention the difference between Iterator and Enumeration.

Iterator Enumeration
Iterator is an interface found in the java.util package.Enumeration is an object that generates elements one at a time.
Uses three methods to interface:

  1. hasNext()
  2. next()
  3. remove()
Uses two methods:

  1. hasMoreElements()
  2. nextElement()
Iterators allow removing elements from the given collection during the iteration with well-defined semantics.It is used for passing through a collection, usually of unknown size.
Iterator method names have been improved.The traversing of elements can only be done once per creation.

14. Explain the difference between the inner class and the subclass.

Inner ClassSubclass
An inner class is a class that is nested within another class.A subclass is a class that inherits from another class called the superclass.
It provides the access rights for the class which is nesting it and that can access all variables and methods defined in the outer class.It provides access to all public and protected methods and fields of its superclass.

 

15. Can we execute any code, even before the main method? Explain.

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

Prepare yourself for Java certification with our comprehensive online Java Training!

16. How can we restrict inheritance for a class?

We can restrict inheritance for a class by the following steps:

  1. By using the final keyword
  2. If we make all methods final, then we cannot override that
  3. By using private constructors
  4. By using the Javadoc comment (//)

17. 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.
Example:

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 class C will take?

As Intellipaat1 and Intellipaat2 class test () methods are different, here we would face ambiguity.

18. 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 superclasses. Because overriding the superclass constructor is not our wish as if we override a superclass constructor, then we will destroy the encapsulation abilities of the language.

Check out this insightful tutorial to learn more about Java Constructors!

19. Define JSON.

The expansion of JSON is ‘JavaScript Object Notation.’ It is a much lighter and readable alternative to XML. It is independent and easily parse-able in all programming languages. It is primarily used for client–server and server–server communication.

20. What are the advantages of JSON over XML?

The advantages of JSON over XML are:

  1.  JSON is lighter and faster than XML.
  2.  It is easily understandable.
  3.  It is easy to parse and convert to objects for information consumption.
  4. JSON supports multiple data types—string, number, array, or Boolean—but XML data are all strings.

21. Name the methods of an object class.

  • clone(): This method helps create and return a copy of an object.
  • equals(): This method helps compare.
  • finalize(): It is called by the garbage collector on the object.
  • getClass(): It allows us to return the runtime class of the object.
  • hashCode(): This method helps return a hash code value for the object.
  • toString(): It lets us return a string representation of the object.
  • notify(), notifyAll(), and wait(): These help in synchronizing the activities of the independently running threads in a program.

Read this tutorial to learn more about Java Methods!

22. Define content negotiation.

If we have visited a website to search for 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 the client and the server negotiate on the language and format of the content to be shared.

23. Can we import the same package/class twice? 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.

24. Define an abstract class.

A class that contains the abstract keyword in its declaration is known as an abstract class. It can have abstract and non-abstract methods (method with a body).

  1.  This class can have public, private, protected, or constants and default variables.
  2.  It needs to be extended and its method needs to be implemented. It cannot be instantiated.
  3.  If a class has at least one abstract method, then the class must be declared abstract.

25. Describe annotations.

  • Java annotation is a tag that symbolizes the metadata associated with class, interface, methods, fields, etc.
  • Annotations do not directly influence operations.
  • The additional information carried by annotations is utilized by Java compiler and JVM.

26. Java doesn't use pointers. Why?

Pointers are susceptible and slightly carelessness in their use which may result in memory problems, and hence Java basically manages their use.

This blog will help you get a better understanding of Mobile Technology for Android and iOS using Java!

27. Distinguish between static loading and dynamic class loading.

    • Static loading: In static loading, classes are loaded statically with the operator ‘new.’
    • Dynamic class loading: It is a technique for programmatically invoking the functions of a class loader at runtime. The syntax for this is as follows:
Class.forName (Test className);

28. Struts 1 classes are not thread-safe, whereas Struts 2 classes are thread-safe. Why?

Struts 1 actions are singleton. So, all threads operate on the single action object and hence make it thread-unsafe.

Struts 2 actions are not singleton, and a new action object copy is created each time a new action request is made and hence it is thread-safe.

29. Define JAXP and JAXB.

JAXP: It 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 of Java objects as XML and for creating Java objects from XML structures.

Learn more about Java Multithreading from this tutorial!

30. Define an enumeration?

Usually, we call 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.

CTA

Watch this video to know why we should learn Java:

Top Java Interview Questions and Answers Want to Learn Java? Click Here

Learn for free ! Subscribe to our youtube Channel.

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

32. Which API is provided by Java for operations on a set of objects?

Java provides a Collection API that provides many useful methods, which can be applied to a set of objects. Some of the important classes provided by the Collection API include ArrayList, HashMap, TreeSet, and TreeMap.

33. What’s the base class of all exception classes?

Java.Lang.throwable: It is the superclass of all exception classes, and all exception classes are derived from this base class.

Learn all about arrays from this comprehensive Java tutorial!

34. Why do we use a vector class?

A vector class provides the ability to execute a growable array of objects. A vector proves to be very useful if you don’t know the size of the array in advance or if we need one that can change the size over the lifetime of a program.

35. What is the difference between transient and volatile variables in Java?

Transient: In Java, it is used to specify whether a variable is not being serialized. Serialization is a process of saving an object’s state in Java. When we want to persist the object’s state by default, all instance variables in the object are stored. In some cases, we want to avoid persisting a few variables because we don’t have the necessity to transfer across the network. So, we declare those variables as transient.

If the variable is confirmed as transient, then it will not be persisted. The transient keyword is used with the instance variable that will not participate in the serialization process. We cannot use static with a transient variable as they are part of the instance variable.

Volatile: The volatile keyword is used with only one variable in Java, and it guarantees that the value of the volatile variable will always be read from the main memory and not from the thread’s local cache; it can be static.

36. Why Map interface does not extend the Collection interface in the Java Collections Framework?

The Map interface is not compatible with the Collection interface, because Map requires a key as well as a value, for example, if we want to add a key–value pair, 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, and other suitable methods that have just different views from the Collection interface.

37. Mention the uses of the synchronized block.

We use the synchronized block because:

  •  It helps lock an object for every shared resource.
  •  The scope of the synchronized block is smaller than the method.

38. What are the functions of hashCode() method?

The hashCode() method returns a hash code value (an integer number) and also the same integer number if the two keys (by calling the equals() method) are the same.
But sometimes, the two hash code numbers can have different or the same keys.

You will get more insights on Java on our Java Community!

39. What is the default size of the load factor in the hashing-based collection?

Default size = 0.75

Default capacity = initial capacity * load factor

40. What are the differences between the JSP custom tags and 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 beans do.
  • Custom tags are available only in JSP 1.1 and so on, but beans can be used in all JSP 1.x versions.

41. Explain the expression language in JSP.

The expression language is used in JSP to simplify the accessibility of objects. It provides many objects that can be used directly like param, requestScope, sessionScope, applicationScope, request, session, etc.

42. What are implicit objects?

Implicit objects, also called pre-defined variables, are created by the JSP engine inside the service method so that it can be accessed directly without being declared explicitly.

43. Define a cookie. What are the differences between a session and a cookie?

A cookie is a small piece of information, which is sent to the browser by a web server. The browser stores the cookies for every web server in a local file. In a future request, the browser sends all stored cookies for that detailed web server.

The difference between cookies and sessions are:

  •  A session works regardless of the settings on the client browser. The client may have selected to disable cookies.
  •  Sessions 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.

44. What is HTTP Tunneling?

HTTP tunneling refers to encapsulating the private network data/information and transmitting it through a public network. Instead of sending data as a packet, tunneling encrypts the data and encapsulates it in a connection. This process allows the outside clients to collect all the data sent by the client-side Object Request Broker (ORB) that needs to be sent to the server-side ORB. HTTP tunneling masks other protocol requests as HTTP requests.

45. What is the function of the IOC container in spring?

The IOC container is responsible for:

  • Creating an instance
  • Configuring the instance
  •  Assembling the dependencies

46. What is lazy loading in hibernate?

Lazy loading is a kind of setting that decides whether to load the child entities along with the parent entities or not. When enabling this feature, the associated entities will be loaded only when they are requested directly. The default value of this setting is ‘true’ which stops the child entities from loading.

47. How can we fetch records using 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

CTA

Watch this Java Tutorial video by Intellipaat:

Top Java Interview Questions and Answers Want to Learn Java? Click Here

Learn for free ! Subscribe to our youtube Channel.

48. Which is the front controller class of Spring MVC?

The Dispatcher Servlet class works as the front controller in Spring MVC.

49. What are the states of an object in hibernate?

The states of an object in hibernate are:

  1. Transient: The objects that are just created having no primary key are in a transient state. Here the objects are associated with any session.
  2. Persistent: When the session of an object is just opened and its instance is just saved or retrieved, it is said to be in a persistent state.
  3. Detached: When the session of an object is closed, it is said to be in a detached state.

50. 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”.

51. What is hash-collision in a HashTable? How is 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 is used to hold the different keys of the same hash value.

52. Write a syntax to convert a given collection to a SynchronizedCollection.

The following will convert a given collection to a synchronized collection:

Collections.synchronizedCollection(Collection collectionObj)

53. Write a code to make the Collections read-only.

We can make the Collections read-only by using the following lines code:

General : Collections.unmodifiableCollection(Collection c)Collections.unmodifiableMap(Map m)
Collections.unmodifiableList(List l)
Collections.unmodifiableSet(Set s)

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

55. What are latest features introduced in Java 8?

The below features are introduced in Java 8:

  • Lambda Expressions
  • Interface Default and Static Methods
  • Method Reference
  • Parameters Name
  • Optional Streams
  • Concurrency

56. Name a few Java 8 annotations.

@Functional Interface annotation: It was introduced in Java SE 8, which 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, @Repeatable annotation indicates that the marked annotation can be applied many times to the same declaration or type use.

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

58. 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));
}

59. What is Nashorn in Java 8?

With Java 8, Nashorn, a much-improved JavaScript engine, is introduced and it replaced the existing Rhino. It provides 2–10 times better performance, as it directly compiles the code in memory and passes the bytecode to JVM. Although, Nashorn uses the invoke dynamic feature, introduced in Java 7, to improve performance.

60. Define a StringJoiner and write a sample code.

StringJoiner is a util method to construct a string with the desired delimiter.

Sample CodeStringJoiner strJoiner = new StringJoiner(".");
strJoiner.add("AAA").add("BBB");
System.out.println(strJoiner);
OutPut:
AAA.BBB

61. Can you execute the JavaScript code from Java 8 code base?

Yes! We can execute the JavaScript code from Java 8 code base by using ScriptEngineManager. We call JavaScript code and interpret it in Java.

19 thoughts on “Top Java Interview Questions and Answers”

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

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

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

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

  5. 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?

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

Leave a Reply

Your email address will not be published. Required fields are marked *

Interview Questions