Skip to content

ADVERTISEMENT

Home » Blogs » Java Interview Questions for 5 Years Experience (40 Questions Covered!)

Java Interview Questions for 5 Years Experience (40 Questions Covered!)26 min read

Java Interview Questions for 5 Years Experience

Introduction

In this blog post, we will cover 40 Java Interview Questions for 5 Years Experience that you may be asked, along with detailed answers. These questions cover a range of topics, including core Java concepts, OOP principles, Java 8 features, and Java collections.

Java is a popular programming language used to develop a wide range of applications, from web apps to mobile apps to enterprise software. If you are a Java developer with 5 years of experience, you should practice a variety of questions for your next interview.

ADVERTISEMENT

Also Read: How to Become a Java Developer

10 Core Java Questions and Answers

  1. What are the four pillars of OOP?

There are four pillars of OOP which include:

  1. Abstraction: is the process of hiding unnecessary details and exposing only the essential information about an object. This allows us to focus on the object’s behavior without worrying about its implementation.
  2. Encapsulation: is the process of wrapping an object’s data and behavior into a single unit. This helps to protect the object’s data from being modified directly, and it also makes it easier to reuse the object’s code.
  3. Inheritance: is the process of creating a new class that inherits the properties and behavior of an existing class. This allows us to reuse code and create hierarchies of classes that represent different levels of abstraction.
  4. Polymorphism: is the ability of an object to take on different forms. This allows us to write code that is more generic and reusable, and it also makes it easier to extend our code in the future.

2. What is the difference between a class and an object?

A Class is a blueprint or template for creating objects. It defines the properties and behaviors that all objects of that class will have. An object is an instance of a class. It is a concrete entity that has the properties and behaviors that all object entity that has the properties and behaviors defined by its class.

Here is a concise and descriptive explanation of the difference between a class and an object:

  • A class is a blueprint or template for creating objects. It defines the properties and behaviors that all objects of that class will have.
  • An object is an instance of a class. It is a concrete entity that has the properties and behaviors defined by its class.

For example, the class Car could define the following properties:

  • make
  • model
  • year
  • color

The class Car could also define the following behaviors:

  • accelerate()
  • brake()
  • turn()

3. What is encapsulation?

Encapsulation is one of the four pillars of object-oriented programming (OOP). It is the process of wrapping data and the code that operates on that data into a single unit. This helps to protect the data from being accessed or modified directly, and it also makes it easier to reuse the code.

Encapsulation is mainly used by private variables and public methods. Private variables can only be accessed by the methods. Private variables can only be accessed by the methods of the class in which they are defined. Public methods can be accessed by any code that has access to the class.

4. What is inheritance?

Inheritance is a mechanism in object-oriented programming (OOP) that allows us to create new classes based on existing classes. This allows us to reuse code and create hierarchies of classes that represent different levels of abstraction.

5. What is polymorphism?

Polymorphism is the ability of an object to take on different forms. This allows us to write code that is more generic and reusable, and it also makes it easier to extend our code in the future.

6. What is the difference between an interface and an abstract class?

An interface is a blueprint for a class that defines a set of methods that the class must implement. Whereas an abstract class is a class that contains abstract methods, which are methods that have no implementation.

The main difference between an interface and an abstract class is that an interface cannot contain any implementation, while an abstract class can. This simply means that an interface is more abstract than an abstract class.

Another difference is that a class can implement multiple interfaces, but it can only extend one abstract class. This is because an interface is a contract, while an abstract class is a base class.

7. What is garbage collection?

Garbage collection is a process that automatically manages the memory allocated to objects. It identifies and reclaims memory that is no longer being used by objects, freeing it up for other users.

It is implemented by the Java Virtual Machine (JVM). The JVM monitors the memory allocated to objects, and it reclaims memory when it is no longer needed.

8. What is the difference between a stack and a heap?

The stack and heap are two different areas of memory in Java. The stack is used to store local variables and method call information, while the heap is used to store objects.

The stack is a last-in-first-out (LIFO) data structure, which means that the last item pushed onto the stack is the first item and the first item is popped off.

The stack is typically smaller than the heap, and it is used to store temporary data. The heap is larger than the stack, and it is used to store long-lived data such as objects.

We can understand it more easily with the following table:

FeatureStackHeap
SizeTypically smallerTypically larger
Data typeLocal variables, method call informationObjects
Memory allocationStaticDynamic
LifespanTemporaryLong-lived

9. What is the Java Virtual Machine (JVM)?

The Java Virtual Machine (JVM) is a software program that executes Java bytecode. Java bytecode is a low-level code that is generated by the Java compiler from Java source code.

10. What is the difference between a checked and an unchecked exception?

A checked exception is a type of exception that the compiler forces the programmer to handle. An unchecked exception is a type of exception that the compiler does not force the programmer to handle.

Checked exceptions are typically used for errors that can be reasonably expected to be handled by the programmer. For example, if a programmer tries to read a file that does not exist, the compiler will throw a checked exception. A programmer can handle this error by just displaying a message to the user or trying to read a different file.

Unchecked exceptions are typically used for errors beyond the programmer’s control. For example, if a programmer tries to divide by zero, the compiler will throw an unchecked exception. A programmer cannot handle this error and the program will typically terminate.

Here is a table to summarize the key differences between checked and unchecked exceptions:

FeatureChecked ExceptionUnchecked Exception
Compiler checkRequiredNot required
Can be handledYesNo
Typically caused byProgrammer errorRuntime error

10 OOP Principles Questions

11. What is the difference between public, protected, and private access modifiers?

The access modifiers in Java are public, protected, and private.

  • Public: Public members of a class can be accessed by any code in the program.
  • Protected: Protected members of a class can be accessed by code within the same class, subclasses of the class, and other classes in the same package.
  • Private: Private members of a class can only be accessed by code within the same class.

We can illustrate this more clearly with the following table:

Access ModifierAccessibility
PublicAccessible by any code in the program
ProtectedAccessible by code within the same class, subclasses of the class, and other classes in the same package.
PrivateAccessible by code within the same class only

12. What is composition?

Composition in Java is a relationship between two objects associated with each other. It is achieved by using instance variables of other objects.

13. What is aggregation?

Aggregation in Java is a type of association between two classes that represents a relationship. It is a weaker form of composition, and it allows two classes to exist independently of each other.

14. What is the difference between a concrete class and an abstract class?

A concrete class is a class that can be observed, meaning that objects can be created from

An abstract class is a class that cannot be observed directly, instead abstract classes are used to define common functionality for other classes to inherit.

Abstract classes typically contain one or more abstract methods, which are methods that do not have an implementation.

Concrete classes must implement all of the abstract methods that they inherit from abstract classes.

We can summarize both of them with the following table:

FeatureConcrete ClassAbstract Class
Can be observed?YesNo
Contains abstract methods?NoYes
Must implement all abstract methods?YesNo

15. What is the difference between an interface and a concrete class?

The main difference between an interface and a concrete class is that an interface is a blueprint or template of a class, while a concrete class is a class that can be observed.

Concrete classes are the building blocks of object-oriented programming. They contain specific data and behavior. Concrete classes can be observed, meaning that objects can be created from them.

Interfaces define a set of methods that a class must implement. Interfaces cannot be observed directly, but they can be implemented by concrete class.

We can understand it more clearly with the help of the following table:

FeatureInterfaceConcrete Class
Can be observed?NoYes
Contains abstract methods?YesCan contain abstract methods, but must also contain concrete methods.
Must implement all abstract methods?YesNo

16. What is the difference between a method and a constructor?

A method is a function that is defined inside a class. It can be used to perform specific tasks, such as calculating the sum of two numbers or printing a message to the console. Methods can be called from anywhere in the code, and they can be passed parameters.

A constructor is a special method that is used to initialize an object when it is created. Constructors have the same name as the class they belong to, and they can have parameters. Constructors are called automatically when an object is created, and they cannot be called explicitly.

We can illustrate this with the following table:

FeatureMethodConstructor
Can be called explicitly?YesNo
Used toPerform a specific taskInitialize an object.
Called whenThe code explicitly calls the methodAn object is created
Can have parameters?YesYes

17. What is the difference between a static method and a non-static method?

A static method is a method that belongs to the class itself, rather than to any instance of the class. This means that a static method can be called without first creating an instance of the class.

A non-static method is a method that belongs to an instance of the class. This means that a non-static method can only be called after an instance of the class has been created.

We can summarize both of them with the help of the following table:

FeatureStatic MethodNon-static Method
Can be called without creating an instance of the class?YesNo
Belongs toThe classAn instance of the class

18. What is the difference between a final method and a non-final method?

A final method is a method that cannot be overridden by subclasses. A non-final method is a method that can be overridden by subclasses.

The final method is often used to implement core functionality that should not be changed by subclasses. For example, the toString() method in the Object class is a final method. This ensures that all objects have a consistent way of representing themselves as strings.

Non-final methods are typically used to implement functionality that subclasses can customize. For example, the draw() method in the Shape class is a non-final method. This allows subclasses to implement their custom drawing logic.

To Summarize Both of the Concepts refer to the following table:

FeatureFinal MethodNon-Final Method
Can be overridden by subclasses?NoYes
Typically used to implementCore functionality that should not be changedFunctionality that subclasses can customize

19. What is the difference between a synchronized method and a non-synchronized method?

A synchronized method is a method that can only be executed by one thread at a time. A non-synchronized method can be executed by multiple threads at the same time.

Synchronized methods are used to protect shared data from being corrupted by concurrent access. When a thread enters a synchronized method, it acquires a lock on the object that the method belongs to. No other thread can enter the method until the first thread has released the lock.

Non-synchronized methods do not acquire any locks. This means that multiple threads can execute a non-synchronized method at the same time. However, this can lead to data corruption if the method accesses shared data.

Have a look at the following table to understand the concepts well:

FeatureSynchronized MethodNon-Synchronized Method
Acquires a lock on the object?YesNo
Can only be executed by one thread at a time?YesNo
Used to protect shared data?YesNo

20. What is the difference between a volatile variable and a non-volatile variable?

A volatile variable is a variable that is visible to all threads and that is always up-to-date. A non-volatile variable is a variable that is not visible to all threads and that may not be up-to-date.

Volatile variables are used to ensure that changes to a variable are visible to all threads. When a thread changes a volatile variable, the change is immediately visible to all other threads. This is because the Java Memory Model (JMM) guarantees that changes to volatile variables are propagated to all threads.

Non-volatile are not visible to all threads. When a thread changes a non-volatile variable, the change may not be visible to other threads. This is because the JMM does not guarantee that changes to non-volatile variables are propagated to all threads.

We can summarize both the concepts with the following table:

FeatureVolatile VariableNon-volatile Variable
Visible to all threads?YesNo
Always up-to-date?YesNo
Used to ensure that changes to a variable are visible to all threads?YesNo

10 Java 8 Features Questions

21. What is a lambda expression?

A lambda expression, also known as an anonymous function a short block of code that can be passed as an argument to a method or assigned to a variable. Lambda expressions are similar to methods, but they do not have a name and they can be implemented right in the body of a method.

22. What is a method reference?

A method reference is a way of referring to a method without explicitly naming it. Method references are often used with functional interfaces. A functional interface is an interface that has only one abstract method.

23. What is a stream?

A stream is a sequence of elements that supports various operations (such as filtering, mapping, and reducing) that can be pipelined to produce the desired result. Streams are a powerful tool for processing data in a functional and declarative manner.

24. What are the different types of stream operations?

There are two main types of stream operations:

  1. Intermediate operations: Intermediate operations are used to transform a stream into another stream. They do not produce a result themselves.
  2. Terminal operations: Terminal operations are used to produce a result from a stream. They consume the stream and cannot be used on the same stream again.

25. What are the benefits of using streams?

There are several benefits of using streams in Java:

  • Conciseness: Streams can be used to write more concise code.
  • Expressiveness: Streams can be used to write more expressive code.
  • Reusability: Streams can be reused to perform multiple operations on the same data.
  • Parallelism: Streams can be used to perform operations in parallel. This can improve the performance of data processing tasks.
  • Immutability: Streams are immutable. This means that they cannot be modified after they have been created. This makes them safe to use in concurrent applications.

26. What is the difference between a mutable and an immutable object?

A mutable object is an object that can be changed after it has been created. An immutable object is an object that cannot be changed after it has been created.

Mutable objects are often used when the state of an object needs to be changed.

Immutable objects are often used when the state of an object is not to be changed.

27. What is a functional interface?

A functional interface is an interface that has only one abstract method. This means that a class that implements a functional interface must provide an implementation for the single abstract method in the interface.

Functional interfaces are often used with lambda expressions and method references. A lambda expression is a short block of code that can be passed as an argument to a method or assigned to a variable. A method reference is a way of referring to a method without explicitly naming it.

28. What is the difference between a default method and a static method in an interface?

A default method is a method that has an implementation in an interface. A static method is a method that belongs to the interface itself, rather than to any instance.

Default methods were introduced in Java 8. They allow interfaces to provide implementations for methods, which can then be overridden by classes that implement the interface. This can be useful for providing common functionality that can be reused by multiple classes

Static methods were introduced in Java 8 as well. They allow interfaces to define methods that can be called without first creating an instance of the interface. This can be useful for providing utility methods that are not associated with any particular instance of the interface.

We can summarize both of them with the following table:

FeatureDefault MethodStatic Method
Has an implementation?YesNo
Can be overridden by subclasses?YesNo
Belong toThe interface and its instancesThe interface itself

29. What is the Optional class?

The Optional class is a container object that may or may not contain a non-null value. It was introduced in Java 8 to provide a safe and idiomatic way to deal with null values.

30. What are the benefits of using the Optional class?

There are several benefits to using the Optional class in Java:

  • Prevents null pointer exceptions: The Optional class can be used to prevent null pointer exceptions by explicitly representing the absence of a value.
  • Improves readability: The Optional class can make code more readable by making it clear when a value may or may not be present. This can help to reduce the amount of mental effort required to understand code.
  • Provides a consistent way to handle null values: The Optional class provides a consistent way to handle null values across different parts of a codebase. This can help to make code more maintainable and easier to understand.
  • Supports functional programming: The Optional class can be used to support functional programming techniques such as map(), filter(), and reduce(). This can help to make code more concise and expressive.

Overall, the Optional class is a valuable tool that can be used to write better Java code.

10 Java Collections Questions

31. What are the different types of Java collections?

Java provides a rich collection of frameworks that includes a variety of collection classes and interfaces. These collections can be used to store and manipulate data in a variety of ways.

Here are some of the most common types of Java collections:

  • Lists: Lists are ordered collections of elements that can be accessed by index. Some common list implementations include ArrayList, LinkedList, and Vector .
  • Sets: Sets are collections of unique elements. Some ****common set implementations include HashSet, TreeSet, and LinkedHashSet.
  • Maps: Maps are collections of key-value pairs. Some common map implementations include HashMap, TreeMap, and LinkedHashMap.
  • Queues: Queues are collections of elements that are ordered on a first-in, first-out (FIFO) basics. Some common queue implementations include LinkedList, PriorityQueue, and ArrayDeque.

32. What is the difference between a List and a Set?

The main difference between a List and a Set is that a List is an ordered collection of elements, while a Set is an unordered collection of unique elements.

In List, elements are stored in a specific order and can be accessed by their index.

In a Set, elements are not stored in a specific order and cannot be accessed by their index.

33. What is the difference between an ArrayList and a LinkedList?

ArraysLists are generally faster for random access operations, such as getting or setting the element at a specific index. This is because ArrayLists can directly access the element at any index in the array.

LinkedLists are generally faster for insertion and deletion operations, especially when the insertions or deletions are not at the end of the list. This is because LinkedLists do not need to shift all of the elements in the list to make room for a new element or to remove an element.

We can summarize both the concepts with the following table:

FeatureArrayListLinkedList
Underlying data structureArrayLinked list
Random accessFastSlow
Insertion and deletionSlowFast
Memory usageMore efficientLess efficient
Thread SafetyNot thread-safeNot thread-safe

34. What is the difference between a HashMap and a TreeMap?

In a HashMap, the order in which key-value pairs are stored is not guaranteed. This means that the order in which elements are iterated over is not predictable. HashMaps are typically used when the order of elements is not important.

In a TreeMap, key-value pairs are stored in a sorted order. The sorting order is determined by the natural ordering of the keys, or by a Comparator that is provided when the TreeMap is created. TreeMaps are typically used when the order of elements is important.

We can summarize HashMap and TreeMap with the following Table:

FeatureHashMapTreeMap
OrderUnorderedOrdered
SortingNo sortingSorted by natural ordering of keys or by Comparator
PerformanceFaster for insertion and deletionSlower for insertion and deletion
Memory usageMore memory-efficientLess-memory-efficient
Thread safetyNot thread-safeNot thread-safe

35. What is the difference between a HashSet and a TreeSet?

In a HashSet, the order in which elements are stored is not guaranteed. This means that the order in which elements are iterated over is not predictable. HashSets are typically used when the order of elements is not important.

In a TreeSet, elements are stored in a sorted order. The sorting order is determined by the natural ordering of the elements, created. TreeSets are typically used when the order of elements is important.

Here is a table to differentiate between HashSets and TreeSets:

FeatureHashSetTreeSet
OrderUnorderedOrdered
SortingNo sortingSorted by natural ordering of elements or by Comparator
PerformanceFaster for insertion and deletionSlower for insertion and deletion
Memory usageMore memory-efficientLess memory-efficient
Thread safetyNot thread-safeNot thread-safe

36. What is the difference between a concurrent and non-concurrent collection?

Non-current collections are not designed to be used by multiple threads. If multiple threads attempt to modify a non-concurrent collection at the same time, the collection can become corrupted. This can lead to data loss or other problems.

Concurrent collections are designed to be used safely by multiple threads. Concurrent collections use a variety of techniques to prevent data corruption, such as locking and atomic operations.

We can summarize both the concepts with the following table:

FeatureConcurrent collectionNon-concurrent collection
Thread safetySafe for use by multiple threadsNot safe for use by multiple threads
PerformanceSlowerFaster
Memory usageMore memory-efficientLess memory-efficient

37. What is the difference between a thread-safe and a non-thread-safe collection?

A thread-safe collection is a collection that can be safely accessed by multiple threads without the need for external synchronization. This means that the collection will not be corrupted if multiple threads attempt to modify it at the same time.

A non-thread-safe collection is a collection that cannot be safely accessed by multiple threads without the need for external synchronization. This means that the collection may be corrupted if multiple threads attempt to modify it at the same time.

Here is a table to summarize both of the topics:

FeatureThread-safe collectionNon-thread-safe collection
Thread safetySafe for use by multiple threadsNot safe for use by multiple threads
External synchronizationMay or may not require external synchronizationRequires external synchronization
PerformanceMay or may not be as performant as concurrent collectionsTypically more performant than thread-safe collections

38. What is the difference between a synchronized and a concurrent collection?

In a synchronized collection, all methods are synchronized. This means that only one thread can be executing a method on the collection at a time. This can lead to performance problems if multiple threads are attempting to access the collection at the same time.

In a concurrent collection, methods are designed to be thread-safe without the need for external synchronization. This is typically achieved by using techniques such as locking and atomic operations. Concurrent collections are typically more performant than synchronized collections when used by multiple threads.

Have a look at the following table to differentiate between synchronized and concurrent collections:

FeatureSynchronized collectionConcurrent collection
Thread safetyMade thread-safe by using external synchronizationDesigned to be thread-safe without the need for external synchronization
PerformanceTypically slower than concurrent collectionsTypically faster than synchronized collections
Memory usageTypically more memory-efficient than concurrent collectionsTypically less memory-efficient than synchronized collections

39. What is the difference between a CopyOnWriteArrayList and an ArrayList?

In an ArrayList, multiple threads can access and modify the list at the same time. This can lead to data corruption if the threads are not carefully synchronized. For example, if one thread is adding an element to the list while another thread is removing an element from the list, it is possible for the list to become corrupted.

In a CopyOnWriteArrayList, modifications to the list are made by creating a copy of the list. The original list is not modified. This ensures that the list cannot be corrupted by multiple threads. For example, if one thread is adding an element to a CopyOnWriteArrayList while another thread is removing an element from the list, the two threads will be working on different copies of the list, the two threads will be working on different copies of the list. The original list will not be modified.

We can Summarize both the concepts with the table given below:

FeatureCopyOnWriteArrayListArrayList
Thread SafetyThread-safeNot thread-safe
PerformanceSlowerFaster
Memory usageMore memory-efficientLess memory-efficient

40. What is the difference between a ConcurrentHashMap and a HashMap?

In a HashMap, multiple threads can access and modify the map at the same time. This can lead to data corruption if the threads are not carefully synchronized. For example, if one thread is adding an entry to the map while another thread is removing an entry from the map, it is possible for the map to become corrupted.

In a ConcurrentHashMap, modifications to the map are made by using a technique called “lock striping”. Lock striping is a technique that divides the map into several segments. Each segment is protected by its lock. This allows multiple threads to modify the map at the same time without the need for external synchronization.

Here is a table to differentiate between ConcurrentHashMap and HashMap:

FeatureConcurrentHashMapHashMap
Thread safetyThread-safeNot thread-safe
PerformanceSlowerFaster
Memory usageMore memory-efficientLess memory-efficient

Conclusion

In this post, we covered 40 Java Questions asked in Interviews with various Java Topics that may be asked for a position with 5 years of experience. By practicing these questions and understanding the answers, can increase your chances of success in your next interview.

ADVERTISEMENT

Leave a Reply