CTA

Java is one of the widely used programming languages in the industry. There are more than 3 billion devices that use Java for their software development. A plethora of job opportunities are available for Java Developers. In this Java Interview Questions blog, you will go through the top Java interview questions that you will come across in Java interviews. Let us have a glance at a few of the important Java interview questions here:

Q1. What do you understand by Java?

Q2. Compare between Java and Python

Q3. Outline the major Java features.

Q4. What do you mean by an object?

Q5. What is a class in Java?

Q6. Differentiate between JDK, JRE, and JVM.

Q7. Define inheritance.

Q8. Explain method overloading.

Q9. Compare overloading with overriding.

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

This blog on Java Interview Questions is categorized into three parts as mentioned below:

1. Basic

2. Intermediate

3. Advanced

Watch this Java Interview Questions video:

Top 100 Java Interview Questions and Answers Top 100 Java Interview Questions and Answers

Learn for free ! Subscribe to our youtube Channel.

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

Criteria Java Python Ease of use Good Excellent Speed of coding Average Excellent Data types Static typed Dynamically typed Data Science and Machine Learning applications Average Excellent

3. Outline the major Java features.

The major features of Java programming language are explained below:

Object-oriented: Java is based on object-oriented programming where the class and methods describe the state and behavior of an object.

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.

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.

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.

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!

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. Distinguish between StringBuffer and StringBuilder in Java programming.

StringBuffer StringBuilder 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!

6. Differentiate between JDK, JRE, and JVM.

JVM stands for Java Virtual Machine which provides the runtime environment for Java bytecodes to be executed.

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.

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

12. Differentiate between an ArrayList and a Vector.

ArrayList Vector 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: hasNext() next() remove() Uses two methods: hasMoreElements() 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 Class Subclass 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:

By using the final keyword If we make all methods final, then we cannot override that By using private constructors 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 { /* Code */ }

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:

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

Intermediate Interview Questions

21. Differentiate between this() and super() in Java.

this() super() Represents the present instance of a class Represents the current instance of the parent class Calls the default constructor Calls the base class constructor Used to point to the current class instance Used to point to the instance of the superclass

22. Name the methods of an object class.

clone() : This method helps create and return a copy of an object.

: This method helps create and return a copy of an object. equals() : This method helps compare.

: This method helps compare. finalize() : It is called by the garbage collector on the object.

: It is called by the garbage collector on the object. getClass() : It allows us to return the runtime class of the object.

: It allows us to return the runtime class of the object. hashCode() : This method helps return a hash code value for the object.

: This method helps return a hash code value for the object. toString() : It lets us return a string representation of the object.

: 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!

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

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

25. 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).

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

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

27. 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!

28. 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);

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

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

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

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

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

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

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

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

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

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

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

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

Default size = 0.75

Default capacity = initial capacity * load factor

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

Advanced Interview Questions

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

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

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

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

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

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

48. 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:

ResultSetExtractor RowMapper

CTA

Watch this Java Tutorial for Beginners video:



Top 100 Java Interview Questions and Answers Top 100 Java Interview Questions and Answers

Learn for free ! Subscribe to our youtube Channel.

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

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

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

The states of an object in hibernate are:

Transient: The objects that are just created having no primary key are in a transient state. Here the objects are associated with any session. 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. Detached: When the session of an object is closed, it is said to be in a detached state.

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

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

53. 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)

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

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

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

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

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

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

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

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

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

63. What is the use of batch processing in JDBC?

Batch processing is a technique that is used to group a set of related SQL queries and execute them in order. This is done to avoid the execution of a single query at a time.

Making use of batch processing ensures that the queries execute faster, thereby maintaining the high efficiency and overall speed of execution.

64. What are the types of statements supported by JDBC?

There are three types of statements supported by JDBC as shown below:

Statement: Used to execute static queries and for general access to the database

CallableStatement: Provides access to stored procedures and runtime parameters

PreparedStatement: Provides input parameters to queries while they are executing

65. What is a collection in Java?

A collection is a framework that is used to store and manipulate a container of objects in Java.

Collections can be used for performing a variety of operations such as:

Search

Sort

Manipulate

Delete

Below is the chart that represents the hierarchy of collections in Java:

66. What is the meaning of constructor overloading in Java?

Constructor overloading is a technique that is popular among programmers who have a requirement of adding multiple constructors to a single class with a different parameter list.

The following denotes an example of constructor overloading:

class Hello { int i; public Hello(int x) { i=k; } public Hello(int x, int y) { /* Set of Instruction */ } }

To clear your doubts you can visit Intellipaat’s Java Community!