Sep 16, 2024

Java Interview Questions for 2 to 5 Years Experience

In this post, we are going to cover the most frequently asked Java interview questions for a 2 to 5 years experienced Java developer. It contains interview questions not only from common Java topics like arrays, strings, threads, and OOPs but also from Java 8, NIO, Spring Boot, Design Patterns, etc. 


This list contains interview questions suitable for both beginners in Java programming and experienced developers with years of experience.


Basic Java


1. What is a String in Java?

A String in Java is a sequence of characters. It’s an object of the String class and is immutable, meaning once you create a string, it cannot be changed. If you modify a string, a new object is created in memory.

2. How does String pooling work in Java?

String pooling is a way using which Java optimizes memory by storing all the string literals in a pool. When we create a string using double quotes, Java checks if the string already exists in the pool. If it does, it reuses the same string object instead of creating a new one. But if we use new String(), it always creates a new object outside of the pool.

3. What is the difference between == and .equals() in strings?

In Java, == compares the reference of two objects, meaning it checks if both objects point to the same location in a memory or not. On the other hand, .equals() method checks if the content of two strings is the same. So, if you want to compare the actual value of strings, you should use .equals().

4. What is the difference between an array and an ArrayList?

An array has a fixed size, meaning once we declare an array, we cannot change its size. An ArrayList, on the other hand, is a part of the java.util package and can dynamically grow and shrink in size. ArrayList provides more flexibility, and it has many useful methods like add(), remove(), and size().

5. How do you sort an array in Java?

In Java, you can sort an array using the Arrays.sort() method from the java.util package. This method sorts the array in ascending order. If you want to sort an array of objects or use custom sorting, you can use Arrays.sort() with a Comparator.



OOPs Concept


6. What do you mean by inheritance in Java?

Inheritance in Java is an Object-Oriented Programming concept that allows a class called child class or subclass to inherit the properties and behaviors of another class called parent class or superclass. It makes code reusable by enabling the creation of a new class based on an existing class. The subclass can access the fields and methods of the superclass, adding its own features or overriding existing ones.


7. What is the difference between Method Overriding and Method Overloading in Java?

Method Overloading is like having multiple methods in the same class with the same name but different parameters. Java determines which method to call based on the number or type of arguments. On the other hand, Method Overriding occurs when a subclass provides a specific implementation for a method that is already present in its superclass. In method overriding method signature is same in both the superclass and subclass.

8. What is runtime polymorphism in Java?

Runtime polymorphism, also known as dynamic method dispatch, occurs when a parent class reference is used to refer to a child class object. The method called is determined at runtime, based on the actual type of the object. 

9. Is it possible to override a static method in Java?

No, it's not possible to override a static method in Java. When a method is static, it belongs to the class rather than an instance of the class. Inheritance and polymorphism, which are essential for method overriding, are associated with objects. As a result, static methods are associated with the class itself and do not participate in overriding.

Explore more ðŸ‘‰ OOPs Interview Questions.


Collections


10. What is ArrayList in Java?

ArrayList in Java is a dynamic array that provides a resizable array. It implements the List interface, which makes it an ordered type of collection. The ArrayList resizes its array dynamically, which simply means it increases its size dynamically when the ArrayList gets full.

11. What is the difference between ArrayList and LinkedList in Java?

ArrayListLinkedList
ArrayList uses a dynamic array to store the elements.LinkedList uses a doubly-linked list to store the elements.
ArrayList provides fast random access.LinkedList is faster at insertion and deletion operations.
It is not good choice for insertion and deletion in the middle.and It is not good choice for random access operations.


12. What is the difference between Iterator and ListIterator?

Iterator and ListIterator are both interfaces in Java used to iterate over collections. The primary  differences are:

IteratorListIterator
We can use Iterator in List, Set and Queue.ListIterator is specific to List only.
Iterator traverses the elements in the forward direction only.Using ListIterator we can traverse the elements in both backward and forward directions.
It Has only hasNext() and next() methods for moving forward.It provides methods like previous(), hasPrevious() in addition to next() and hasNext() for moving in both directions.
While traversing the collection using Iterator we can perform only remove operation.Here we can perform add, remove and set operation while traversing the collection.


13. What is the difference between HashSet and TreeSet?

HashSetTreeSet
ArrayList uses a dynamic array to store the elements.LinkedList uses a doubly-linked list to store the elements.
ArrayList provides fast random access.LinkedList is faster at insertion and deletion operations.
It is not good choice for insertion and deletion in the middle.and It is not good choice for random access operations.


14. What is the hashCode() method?

The hashCode() method in Java is used to generate a unique integer value (the hash code) for an object. This hash code is used when storing objects in hash-based collections like HashMap, HashSet, or Hashtable. Like based on the hashcode the index of the object gets calculated.

15. What is hash-collision in Hashtable, and how is it handled in Java?

Hash-collision in a Hashtable occurs when two different keys generate the same hash code, which leads them to be stored in the same bucket. In Java, this is a common issue and To handle hash-collision, Java uses a technique called chaining. In this method, each bucket contains a linked list of all the entries that have the same hash code. When a collision happens, the new entry is added to the linked list.


16. What is the difference between Set and Map?

Set and Map are both interfaces in Java Collections Framework. A Set is a collection that does not allow duplicate elements, while a Map is a collection of key-value pairs where each key must be unique. In simpler terms, Set stores individual elements, while Map associates each element with a key.

17. What do you understand by fail-fast?

Fail-fast in Java is a concept where an iterator quickly detects any changes made to the structure of a collection while it is being iterated. If the collection is modified like adding or removing elements during iteration, the iterator throws a ConcurrentModificationException. This helps to warn the programmer that something went wrong because the collection was changed while it was still being looped over. It prevents unexpected behavior or bugs that can happen when multiple operations try to modify the collection at the same time.

18. How to remove duplicates from ArrayList?

To remove duplicates from an ArrayList, we can convert it to a Set, as Sets do not allow duplicates. 
Here are the steps to remove duplicates from ArrayList using the LinkedHashSet:

Step 1: Copy all the elements of ArrayList to LinkedHashSet(So LinkedHashSet will remove all duplicates automatically).
Step 2: Empty the ArrayList using the clear() method.
Step 3: Copy back all elements of LinkedHashSet to ArrayList.

NOTE: Here we can also use HashSet instead of  LinkedHashSet but it will not maintain insertion order.



Multithreading


19. What is multithreading in Java, and how does it work?

Multithreading in Java means running multiple threads concurrently to achieve better performance. A thread is the smallest unit of a process, and by using multiple threads, you can execute different parts of your program at the same time. This is useful for tasks like handling multiple users on a web server or running background tasks while the main program is running, which enhances efficiency and performance of the application.

20. How can you create a thread in Java?

In Java, we can create a thread using two main ways:

By extending the Thread class and overriding its run() method.

By implementing the Runnable interface and passing it to a Thread object.

But using the Runnable interface is generally preferred as it allows more flexibility.


21. What is the difference between Thread class and Runnable interface?

Both Thread class and Runnable interface are used to create and run threads in Java, but there is a difference. Like when we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple inheritance. On the other hand, using the Runnable interface allows us to implement other interfaces or extend another class since multiple inheritance is supported using interfaces in Java.


22. What is a synchronized block in Java?

A synchronized block is used to control the access of multiple threads to shared resources. It ensures that only one thread can execute a particular block of code at a time which helps to prevent data inconsistency issues. For example, if multiple threads try to modify the same data at the same time, the synchronized block will make sure that one thread completes its work before another can access that data.



Exception Handling


23. What is Exception Handling in Java?

An unexpected or unwanted event that disturbs the normal flow of the program is called an exception. For example, when dividing by zero or accessing an invalid array index, Java throws an exception. So Exception handling in Java is a mechanism to manage this type of runtime errors.  Instead of letting the program crash, we can use exception handling to "catch" these exceptions and decide how to deal with them. This helps the program to continue its flow normally.


24. What does the "try-with-resources" statement do in Java?

The try-with-resources statement in Java is used to automatically close resources like files, database connections, or streams after they are used. Normally when you open a resource, you have to manually close it in a finally block to avoid memory leaks. But with try-with-resources, Java automatically takes care of closing the resource for you once the try block is done.


25. What is the difference between checked and unchecked exceptions?

Checked exceptions are exceptions that are checked at compile time. These are exceptions that the programmer needs to handle using try-catch or by declaring them with the throws keyword. For example, IOException is a checked exception. Unchecked exceptions, on the other hand, are not checked at compile time but happen during runtime. These include exceptions like NullPointerException and ArrayIndexOutOfBoundsException. 


26. What is a try-catch block in Java?

A try-catch block is used to handle exceptions. Code that might throw an exception is placed inside the try block, and the catch block is used to handle the exception if it occurs. If an exception happens in the try block, the program will skip the rest of the block and jump to the catch block, where the error can be handled without crashing the program.


27. What is the purpose of the finally block?

The finally block always executes no matter if an exception was thrown or not. It is mainly used for clean-up actions like closing files or releasing resources. Even if there is a return statement in the try or catch block, the finally block will still be executed.


28. What is the difference between throw and throws?

throw is used to manually throw an exception, while throws is used in a method signature to declare that the method might throw certain exceptions. When a method has a throws declaration, it means that the caller of that method is responsible for handling the exception.



Java 8


29. What is the purpose of the default method in interfaces in Java 8?

In Java 8, default methods were introduced in interfaces. A default method is a method that has a body, and we don’t have to implement it in the classes that implement the interface. This was added mainly for backward compatibility, so that we can add new methods to interfaces without breaking the existing implementations.


30. What are lambda expressions in Java 8?

A lambda expression is a short way to define an anonymous function, meaning it is a method without a name, access modifiers and return type. It lets you write cleaner code and specially used to provide the implementation of functional interfaces like Runnable or Comparator. For example, (a, b) -> a + b is a simple lambda that adds two numbers.


31. What is a functional interface in Java 8?

A functional interface is an interface that has only one abstract method. In Java 8, these are used a lot with lambda expressions. For example, Runnable and Comparator are functional interfaces. The @FunctionalInterface annotation can be used to mark an interface as functional, but it’s not required.


32. Explain Stream API in Java 8?

Stream API in Java 8 is used to process data in a functional programming style. It helps to process data of collections in a very easy way. We can filter, map, and reduce data using streams.


33. How does method reference work in Java 8?

A method reference is a shorthand for a lambda expression that calls a method. It is used to make the code even more readable. Method references use the :: symbol. For example, instead of writing x -> System.out.println(x) you can simply write System.out::println.


34. What are the main differences between Optional and null in Java 8?

In Java 8, Optional is a container that might or might not contain a value. Instead of using null to represent the absent values, we can use Optional to avoid NullPointerException. We can also check if value is present or not using methods like isPresent() and handle cases where a value might be missing in a much cleaner way.


35. What is the use of the Collectors.toList() in Java 8?

The Collectors is a class and toList() is a method in the Stream API that collects the elements of a stream into a List. For example, you can use stream().filter().collect(Collectors.toList()) to filter a stream and get the results as a list.



File Handling

 

36. What is file handling in Java?

File handling in Java allows us to read from and write to files. Java provides classes like File, FileReader, FileWriter, BufferedReader, and BufferedWriter to work with files. We can use these classes to create, read, write, and delete files. File handling is essential when we want to save data permanently or work with external files.


37. How do we create a file in Java?

In Java, we can create a file using the File class from the java.io package. To create a new file, we can use the createNewFile() method. Here’s a simple example:
File file = new File("example.txt");
if (file.createNewFile()) {
    System.out.println("File created successfully");
} else {
    System.out.println("File already exists");
}

 

38. How do we write data to a file in Java?

We can write data to a file using FileWriter or BufferedWriter. FileWriter writes characters directly to the file, and BufferedWriter adds a buffer, which makes writing faster. Here’s a simple example:
FileWriter writer = new FileWriter("example.txt");
writer.write("Hello, World!");
writer.close();

39. What is the difference between FileWriter and BufferedWriter?

FileWriter writes characters directly to the file, while BufferedWriter uses a buffer to store characters before writing them to the file. This makes BufferedWriter faster, especially when writing large amounts of data. If performance is important, then it is recommended to use BufferedWriter.

40. What happens if we try to write to a file that doesn’t exist?

If we try to write to a file that doesn’t exist, then FileWriter will automatically create the file. We don’t need to explicitly create the file before writing. But if the file already exists, it will overwrite the existing content unless we pass true as the second argument to FileWriter to enable append mode.



Spring Boot Framework


41. What is Spring Boot and why do we use it?

Spring Boot is an extension of the Spring Framework that simplifies the development of Spring-based applications. It helps us create stand-alone, production-ready applications with minimal configuration. We use Spring Boot because it reduces the boilerplate code and configuration, which makes it easy to start new projects quickly. It also comes with embedded servers like Tomcat, so we don’t need to deploy the app separately.

42. What are starters in Spring Boot?

Starters in Spring Boot are a set of pre-configured dependencies that we can include in our project to get started quickly. For example, if we want to create a web application, we can add the spring-boot-starter-web dependency, and it will include all necessary libraries like Spring MVC and Tomcat. This helps us avoid manually adding multiple dependencies.

43. What is Spring Boot Auto-configuration?

Auto-configuration in Spring Boot automatically configures beans that we need based on the dependencies present in the classpath. It reduces the need to write a lot of manual configurations. For example, if we include spring-boot-starter-data-jpa in our project, Spring Boot will automatically configure JPA and a DataSource based on the database properties we provide in application.properties.


44. How do we create a Spring Boot application?

We can create a Spring Boot application using Spring Initializr, which is a web-based tool to generate Spring Boot projects. Using this we can choose dependencies, project type (Maven/Gradle), and Spring Boot version. After generating the project, we can import it into an IDE like Eclipse or IntelliJ. Then, we add our business logic, and the application is ready to run.


45. What is the @SpringBootApplication annotation?

The @SpringBootApplication annotation is a combination of three annotations:

@Configuration: Indicates that the class can be used for Java-based configuration.
@EnableAutoConfiguration: Enables auto-configuration in Spring Boot.
@ComponentScan: Scans for Spring components in the current package and sub-packages.
This annotation is placed on the main class of our Spring Boot application.


46. How do we configure properties in Spring Boot?

In Spring Boot, we can configure properties in the application.properties or application.yml file. These files contain key-value pairs that we can use to set configurations like database connections, server port, or logging levels.


47. What is Spring Actuator?

Spring Actuator is a module in Spring Boot that provides production-ready features like monitoring, metrics, and health checks. It helps us monitor and manage our application in real-time.


48. What is Spring Boot Profiles and how do we use them?

Spring Boot Profiles allow us to define different configurations for different environments like development, testing, or production. We can use profiles to change the behavior of the application without modifying the code. To use profiles, we define separate configuration files like application-dev.properties or application-prod.properties, and then we specify the active profile in the application.properties or through the command line.

spring.profiles.active=dev



49. How do we handle exception handling globally in Spring Boot?

In Spring Boot, we can handle exceptions globally using the @ControllerAdvice annotation. It allows us to write a global exception handler for the entire application. Inside @ControllerAdvice, we can use @ExceptionHandler to define specific methods to handle different exceptions.


50. What is Spring Boot Microservices architecture?

Microservices architecture is an approach where we develop small, independent services that work together to form a complete application. In Spring Boot, we use microservices to break down a large application into smaller, manageable services. Each service can run independently and communicate with other services using REST, messaging, or service discovery tools like Eureka.



Database and JDBC


51. What is JDBC and why do we use it?

JDBC (Java Database Connectivity) is an API that allows Java applications to interact with databases. We use JDBC to connect to databases, send SQL queries, and retrieve results. It provides a standard interface for Java programs to communicate with different types of databases like MySQL, Oracle, or PostgreSQL. JDBC acts as a bridge between Java and the database.


52. What are the main components of JDBC API?

JDBC API has four main components:

DriverManager: It manages the database drivers and establishes the connection to the database.
Connection: This interface represents the connection between Java and the database.
Statement: It is used to send SQL queries to the database.
ResultSet: It holds the data retrieved from the database after executing a query.

These components help us to interact with databases in a structured way.


53. What is the difference between Statement and PreparedStatement?

Both Statement and PreparedStatement are used to execute SQL queries, but there are some differences:

Statement: It is used for executing simple SQL queries without parameters. We use it when the query is fixed.
PreparedStatement: It is used when we want to execute the same query multiple times with different parameters. It provides better performance and security against SQL injection.


54. What is ResultSet in JDBC?

A ResultSet is an object that holds the data retrieved from the database after executing a query. It provides methods to iterate through the rows of data and access the column values. We can navigate through the rows using methods like next(), previous(), first(), and last().


55. What is Batch Processing in JDBC?

Batch Processing in JDBC allows us to execute multiple SQL queries as a batch, instead of executing them one by one. This improves performance, especially when inserting or updating large amounts of data. We add multiple queries to a batch using addBatch() and then execute them together using executeBatch()
For Example:
Statement stmt = conn.createStatement();
stmt.addBatch("INSERT INTO users VALUES (1, 'Robert')");
stmt.addBatch("INSERT INTO users VALUES (2, 'Jane')");
stmt.executeBatch();



Design Patterns


56. What are Design Patterns and why do we use them?

Design patterns are readily available solutions to common problems in software design. They provide a standard approach to solve recurring issues, making our code more reusable, maintainable, and flexible. We use design patterns to write cleaner, well-structured code that is easier to understand and modify. They act as templates that we can apply to similar problems in different situations.


57. What is the Singleton Pattern and how do we implement it?

The Singleton Pattern ensures that a class has only one instance and provides a global point of access to it. We use this pattern when we want to restrict the instantiation of a class to a single object, like for database connections or logging. To implement a Singleton, we make the constructor private and provide a static method to return the instance.

Example:
public class Singleton {
    private static Singleton instance;
    private Singleton() {}
    
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}


58. What is the Factory Pattern?

The Factory Pattern is a creational pattern that provides an interface for creating objects, but allows subclasses to alter the type of objects that will be created. We use this pattern when we want to delegate the instantiation process to child classes instead of directly creating objects. The factory method creates and returns objects based on the input we provide.

public interface Vehicle {
    void start();
}

public class Car implements Vehicle {
    public void start() {
        System.out.println("Car is Started.....");
    }
}

public class VehicleFactory {
    public Vehicle getVehicle(String vehicleType) {
        if (vehicleType.equalsIgnoreCase("CAR")) {
            return new Car();
        }
        return null;
    }
}


59. What is the Observer Pattern?

The Observer Pattern defines a one-to-many relationship between objects. When the state of one object (the subject) changes, all its dependents (observers) are notified and updated automatically. We use this pattern when one object needs to notify multiple objects about changes without them tightly depending on each other.

60. What is the Strategy Pattern?

The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. We use this pattern when we have multiple algorithms for a specific task, and we want to choose the algorithm at runtime. This pattern allows us to change the behavior of a class by changing the algorithm it uses.


And there are many more design patterns like the Proxy Pattern, Facade Pattern, Adapter Pattern, etc., which you also need to learn before attending an interview. 

No comments:

Post a Comment

Share your thoughts or ask questions below!...👇

Featured Post

Java Interview Questions for 2 to 5 Years Experience

In this post, we are going to cover the most frequently asked Java interview questions for a 2 to 5 years experienced Java developer. It con...