Java Interview Questions for Freshers PDF

Top 50 Java Interview Questions for Freshers

This Java Interview Questions for Freshers guide helps new graduates and beginners prepare for programming job interviews with questions made especially for freshers starting their career. We included basic Java questions about object-oriented programming, core concepts, and simple coding problems that entry-level positions require.

The guide covers everything from basic syntax and data types to classes and methods that companies test beginners on. Use this guide to practice Java basics and get your first software developer job.

You can also check our another guide here: 100 Java interview Questions and Answers PDF

Basic Java Interview Questions and Answers for Freshers

Que 1. What is the difference between JDK, JRE, and JVM?

Answer:
JDK (Java Development Kit) is a complete package containing tools to develop, compile, and run Java programs. It includes JRE and development tools like compilers.
JRE (Java Runtime Environment) contains the libraries, Java Virtual Machine (JVM), and other components to run Java applications. It does not have development tools.
JVM (Java Virtual Machine) is the engine that runs Java bytecode. It provides platform independence and manages memory and other runtime operations.

ComponentPurposeIncludes
JDKDevelopment and executionJRE + Compiler + Tools
JREExecution onlyJVM + Libraries
JVMExecutes bytecodeNot a physical package

Que 2. How does Java achieve platform independence?

Answer:
Java achieves platform independence through the concept of bytecode. When Java source code is compiled, it is converted into an intermediate form called bytecode. This bytecode is executed by the JVM, which has platform-specific implementations. This means the same bytecode can run on any operating system with a compatible JVM, following the “Write Once, Run Anywhere” principle.

Que 3. What are wrapper classes in Java and why are they used?

Answer:
Wrapper classes are object representations of primitive data types. For example, int has Integer, double has Double, and so on. They are used for:

  • Converting primitive types to objects (autoboxing)
  • Using primitives in collections that store objects (like ArrayList)
  • Providing utility methods for type conversions and value parsing

Example:

int num = 5;  
Integer obj = num; // Autoboxing

Que 4. What is the difference between String, StringBuilder, and StringBuffer?

Answer:

  • String: Immutable, meaning its value cannot change after creation. Operations create new objects.
  • StringBuilder: Mutable and faster for single-threaded operations.
  • StringBuffer: Mutable and thread-safe due to synchronization but slower than StringBuilder.

Que 5. How does the Final keyword work in Java?

Answer:
The final keyword has three main uses:

  • Final variable: Cannot be reassigned once initialized.
  • Final method: Cannot be overridden by subclasses.
  • Final class: Cannot be inherited.

Example:

final int MAX = 100;

Que 6. What is method overloading and method overriding in Java?

Answer:

  • Method Overloading: Same method name, different parameter lists in the same class. Achieved at compile-time.
  • Method Overriding: Same method signature in parent and child class, but different implementation. Achieved at runtime.

Que 7. How does Java handle memory management?

Answer:
Java uses an automatic garbage collection mechanism to manage memory. The JVM identifies and removes unused objects from memory. Memory is divided into heap (for objects) and stack (for method calls and local variables). Developers can suggest garbage collection using system.gc but cannot force it.

Que 8. What is the difference between == and .Equals() in Java?

Answer:

  • ==: Compares references (memory addresses) for objects, or values for primitives.
  • .equals(): Compares the content of objects. Can be overridden for custom comparison.

Que 9. What are Java access modifiers and their scopes?

Answer:
Java has four main access modifiers:

ModifierSame ClassSame PackageSubclass (diff package)Other Packages
publicYesYesYesYes
protectedYesYesYesNo
defaultYesYesNoNo
privateYesNoNoNo

Que 10. How does exception handling work in Java?

Answer:
Java uses try-catch-finally blocks for exception handling:

  • try: Contains code that may throw an exception.
  • catch: Handles specific exceptions.
  • finally: Optional block that executes regardless of exceptions.

Example:

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
} finally {
    System.out.println("Execution complete");
}

Que 11. What is the difference between checked and unchecked exceptions?

Answer:

  • Checked exceptions: Checked at compile time. Must be handled or declared using throws (e.g., IOException).
  • Unchecked exceptions: Occur at runtime. Usually caused by programming errors (e.g., NullPointerException).

Que 12. How does multithreading work in Java?

Answer:
Multithreading allows concurrent execution of two or more threads for maximum CPU utilization. Java supports multithreading via:

  • Extending the Thread class
  • Implementing the Runnable interface

Example:

class MyThread extends Thread {
    public void run() {
        System.out.println("Thread running");
    }
}

Que 13. What is the use of the This keyword in Java?

Answer:
The this keyword refers to the current object instance. It is used to:

  • Differentiate instance variables from parameters
  • Call other constructors in the same class (this())
  • Pass the current object to another method

Que 14. What is the difference between abstract class and interface?

Answer:

  • Abstract class: Can have both abstract and concrete methods, can hold instance variables, supports constructors.
  • Interface: All methods are abstract (until Java 8 default methods), variables are public static final, and no constructors.

Que 15. How does the super keyword work in Java?

Answer:
The super keyword refers to the parent class. It is used to:

  • Call the parent class constructor
  • Access parent class methods and variables hidden by the subclass

Example:

super.methodName();

Advanced Java Interview Questions and Answers for Freshers

Que 16. What is the purpose of the Spring Framework, and how does it simplify Java development?

Answer: The Spring Framework is a powerful, open-source framework that simplifies Java enterprise application development by providing modular components for dependency injection, data access, web development, and more. It reduces boilerplate code and promotes loose coupling, making applications easier to maintain and test.

Key features:

  • Dependency Injection (DI): Manages object creation and dependencies, reducing manual wiring.
  • Spring MVC: Simplifies building web applications with a model-view-controller architecture.
  • Data Access: Provides templates (e.g., JdbcTemplate) to simplify database operations.
  • Configuration: Supports Java-based or XML-based configuration for flexibility.

Example of DI in Spring:

@Component
public class UserService {
    public String getUser() {
        return "User fetched";
    }
}

@Component
public class UserController {
    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    public String fetchUser() {
        return userService.getUser();
    }
}

Key points:

  • Spring reduces manual object creation with @Component and @Autowired.
  • It supports modular development, making it easier for freshers to build scalable applications.
  • Common for web applications, REST APIs, and microservices.

Que 17. What is the difference between checked and unchecked exceptions in Java?

Answer: In Java, exceptions are divided into checked and unchecked categories, based on how they are handled by the compiler.

FeatureChecked ExceptionsUnchecked Exceptions
TypeExtend Exception (not RuntimeException)Extend RuntimeException
Compiler EnforcementMust be declared or handled (try-catch)No compiler enforcement
ExamplesIOException, SQLExceptionNullPointerException, ArrayIndexOutOfBoundsException
Use CaseRecoverable errors (e.g., file not found)Programming errors (e.g., null reference)

Example:

// Checked exception
public void readFile() throws IOException {
    FileInputStream fis = new FileInputStream("file.txt"); // Must handle or declare
}

// Unchecked exception
public void accessArray() {
    int[] arr = new int[5];
    System.out.println(arr[10]); // Throws ArrayIndexOutOfBoundsException
}

Key points:

  • Checked exceptions force developers to handle errors explicitly, improving robustness.
  • Unchecked exceptions indicate bugs that should be fixed during development.
  • Freshers should understand when to catch or propagate exceptions in code.

Que 18. How does Spring Boot differ from the Spring Framework, and why is it useful for beginners?

Answer: Spring Boot is a module of the Spring Framework that simplifies its configuration and setup, making it ideal for beginners building Java applications.

Key differences:

  • Auto-Configuration: Spring Boot automatically configures components (e.g., database, web server) based on dependencies, reducing manual setup.
  • Embedded Server: Includes servers like Tomcat, allowing standalone applications without external server installation.
  • Starter Dependencies: Simplifies dependency management with predefined starters (e.g., spring-boot-starter-web).
  • Minimal Code: Reduces boilerplate code compared to traditional Spring.

Example of a Spring Boot application:

@SpringBootApplication
@RestController
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }

    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, Spring Boot!";
    }
}

Key points:

  • Spring Boot’s simplicity helps freshers focus on business logic rather than configuration.
  • It supports rapid development of REST APIs and microservices.
  • Beginners can use application.properties for easy configuration.

Que 19. What is the purpose of the @Autowired annotation in Spring, and how does it work?

Answer: The @Autowired annotation in Spring enables dependency injection by automatically wiring beans (objects) into a class, eliminating manual instantiation.

How it works:

  • Spring’s IoC (Inversion of Control) container identifies beans marked with @Component, @Service, etc.
  • @Autowired matches dependencies by type or name and injects them into fields, constructors, or setters.
  • It reduces boilerplate code and promotes loose coupling.

Example:

@Service
public class UserService {
    public String getUser() {
        return "User data";
    }
}

@RestController
public class UserController {
    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/user")
    public String fetchUser() {
        return userService.getUser();
    }
}

Key points:

  • @Autowired can be used on constructors (preferred), fields, or setters.
  • It simplifies dependency management for freshers building Spring applications.
  • Use @Qualifier to resolve ambiguity when multiple beans of the same type exist.

Que 20. How does Java’s try-with-resources statement work, and why is it useful?

Answer: The try-with-resources statement, introduced in Java 7, automatically closes resources (e.g., files, database connections) that implement AutoCloseable, preventing resource leaks.

How it works:

  • Resources declared in the try clause are automatically closed when the block exits, even if an exception occurs.
  • It replaces manual try-catch-finally blocks for resource management.

Example:

public void readFile(String path) {
    try (FileInputStream fis = new FileInputStream(path)) {
        int data = fis.read();
        System.out.println("Read: " + data);
    } catch (IOException e) {
        System.out.println("Error: " + e.getMessage());
    }
}

Key points:

  • Simplifies code by eliminating explicit close() calls.
  • Ensures resources are closed promptly, reducing memory leaks.
  • Useful for freshers working with I/O operations or database connections.

Que 21. What is the role of the @RestController annotation in Spring Boot, and how is it different from @Controller?

Answer: The @RestController annotation in Spring Boot marks a class as a controller for handling REST API requests, combining @Controller and @ResponseBody.

Key differences:

  • @Controller: Used for traditional MVC web applications, typically returning view names for rendering templates.
  • @RestController: Designed for REST APIs, automatically serializing return values to JSON/XML.

Example:

@RestController
@RequestMapping("/api")
public class UserRestController {
    @GetMapping("/user")
    public User getUser() {
        return new User(1, "John"); // Automatically converted to JSON
    }
}

@Controller
public class UserController {
    @GetMapping("/user")
    public String getUserView() {
        return "user"; // Returns view name for template rendering
    }
}

Key points:

  • @RestController simplifies REST API development for freshers.
  • Eliminates the need for @ResponseBody on every method.
  • Commonly used in microservices and API-driven applications.

Que 22. How does Hibernate simplify database operations in Java, and what is the role of the @Entity annotation?

Answer: Hibernate is an ORM (Object-Relational Mapping) framework that simplifies database operations by mapping Java objects to database tables, reducing manual SQL queries.

Key benefits:

  • Object Mapping: Maps Java classes to tables and fields to columns.
  • CRUD Operations: Provides APIs for creating, reading, updating, and deleting data.
  • Query Language: Uses HQL (Hibernate Query Language) for database-agnostic queries.

The @Entity annotation marks a class as a database entity, mapping it to a table.

Example:

@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    // Getters, setters
}

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByName(String name);
}

Key points:

  • @Entity enables automatic table creation and mapping.
  • Simplifies database access for freshers using Spring Data JPA.
  • Reduces boilerplate SQL code, focusing on Java logic.

Que 23. What is the purpose of the transient keyword in Java serialization, and how does it work?

Answer: The transient keyword in Java marks a field as non-serializable, excluding it from the serialization process when an object is converted to a byte stream.

How it works:

  • During serialization, transient fields are skipped and not saved.
  • When deserializing, transient fields are set to their default values (e.g., null for objects, 0 for numbers).

Example:

import java.io.*;

public class User implements Serializable {
    private String name;
    private transient String password; // Not serialized

    public User(String name, String password) {
        this.name = name;
        this.password = password;
    }

    // Getters
}

class SerializationDemo {
    public static void main(String[] args) throws Exception {
        User user = new User("Alice", "secret");
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("user.ser"));
        out.writeObject(user);
        out.close();

        ObjectInputStream in = new ObjectInputStream(new FileInputStream("user.ser"));
        User deserialized = (User) in.readObject();
        in.close();
        System.out.println(deserialized.getName()); // Outputs: Alice
        System.out.println(deserialized.getPassword()); // Outputs: null
    }
}

Key points:

  • transient is useful for sensitive data (e.g., passwords) or temporary fields.
  • Simplifies serialization for freshers by controlling what gets saved.
  • Ensures security and reduces serialized object size.

Que 24. How does the Java Stream API simplify data processing, and how can you use it to filter and map a collection?

Answer: The Java Stream API, introduced in Java 8, simplifies data processing by providing a functional approach to manipulate collections in a declarative, concise way.

Key features:

  • Filtering: Selects elements based on a condition.
  • Mapping: Transforms elements into another form.
  • Chaining: Combines operations in a pipeline for readability.

Example:

import java.util.*;
import java.util.stream.Collectors;

public class StreamDemo {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
        List<String> filteredNames = names.stream()
            .filter(name -> name.length() > 3) // Filter names longer than 3 characters
            .map(String::toUpperCase) // Convert to uppercase
            .collect(Collectors.toList());
        System.out.println(filteredNames); // Outputs: [ALICE, CHARLIE, DAVID]
    }
}

Key points:

  • Streams are lazy; operations execute only when a terminal operation (e.g., collect) is called.
  • Simplifies complex data operations for freshers.
  • Avoids modifying the original collection, ensuring immutability.

Que 25. What is the purpose of the @Transactional annotation in Spring, and how does it ensure data consistency?

Answer: The @Transactional annotation in Spring manages database transactions, ensuring that a series of operations either complete successfully or roll back to maintain data consistency.

How it works:

  • Wraps a method or class in a transaction, ensuring atomicity.
  • If an exception occurs, changes are rolled back; otherwise, they are committed.
  • Configured with attributes like propagation and isolation.

Example:

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    @Transactional
    public void updateUser(Long id, String name) {
        User user = userRepository.findById(id).orElseThrow();
        user.setName(name);
        userRepository.save(user); // Rolled back if exception occurs
    }
}

Key points:

  • Ensures data integrity in database operations.
  • Simplifies transaction management for freshers using Spring Data.
  • Use @EnableTransactionManagement in configuration to enable it.

JDK compiles it, JRE provides necessary libraries, and JVM executes the compiled bytecode.

Que 26. What is the purpose of the @Configuration annotation in Spring, and how does it help in setting up a Spring application?

Answer: The @Configuration annotation in Spring marks a class as a source of bean definitions, allowing developers to define and configure Spring beans programmatically instead of using XML configuration. It simplifies setting up a Spring application by providing a Java-based approach to configure the application context.

Key features:

  • Bean Definition: Methods annotated with @Bean in a @Configuration class define Spring-managed beans.
  • Centralized Configuration: Groups all bean definitions in one place for better organization.
  • Type Safety: Java-based configuration avoids XML parsing errors, making it easier for beginners.

Example:

@Configuration
public class AppConfig {
    @Bean
    public UserService userService() {
        return new UserService();
    }

    @Bean
    public UserController userController(UserService userService) {
        return new UserController(userService);
    }
}

@Service
public class UserService {
    public String getUser() {
        return "User data";
    }
}

@Controller
public class UserController {
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }
}

Key points:

  • @Configuration replaces XML-based configuration, making it more intuitive for freshers.
  • @Bean methods return objects that Spring manages as beans.
  • Enables dependency injection by wiring beans together in the configuration class.

Que 27. How does the Java volatile keyword ensure thread safety, and when should it be used?

Answer: The volatile keyword in Java ensures thread safety by guaranteeing visibility and ordering of variable updates across threads, but it does not provide atomicity. It is used for variables shared between threads to ensure all threads see the latest value.

How it works:

  • Visibility: Ensures that changes to a volatile variable are immediately visible to all threads by bypassing thread-local caches.
  • Ordering: Prevents the JVM from reordering instructions involving volatile variables.

Example:

public class SharedFlag {
    private volatile boolean running = true;

    public void stop() {
        running = false; // Immediately visible to all threads
    }

    public boolean isRunning() {
        return running; // Always reads latest value
    }
}

class ThreadDemo {
    public static void main(String[] args) throws InterruptedException {
        SharedFlag flag = new SharedFlag();
        new Thread(() -> {
            while (flag.isRunning()) {
                System.out.println("Running...");
            }
        }).start();
        Thread.sleep(100);
        flag.stop();
    }
}

Key points:

  • Use volatile for simple flags or single-value updates in multi-threaded applications.
  • Does not replace synchronized for complex operations like increment (i++).
  • Helps freshers write basic thread-safe code without complex locking.

Que 28. What is the role of the @RequestMapping annotation in Spring, and how can it be used to handle HTTP requests?

Answer: The @RequestMapping annotation in Spring maps HTTP requests to specific methods or classes in a controller, enabling the handling of web requests in a Spring MVC or Spring Boot application.

Key features:

  • HTTP Methods: Supports specific methods (e.g., GET, POST) using @GetMapping, @PostMapping, etc.
  • Path Mapping: Maps URLs to methods or classes (e.g., /api/users).
  • Flexibility: Supports parameters like produces, consumes, and params for fine-grained control.

Example:

@RestController
@RequestMapping("/api/users")
public class UserController {
    @GetMapping("/{id}")
    public String getUser(@PathVariable Long id) {
        return "User " + id;
    }

    @PostMapping
    public String createUser(@RequestBody User user) {
        return "Created user: " + user.getName();
    }
}

public class User {
    private String name;
    // Getters, setters
}

Key points:

  • @RequestMapping simplifies REST API development for freshers.
  • @PathVariable and @RequestBody extract URL parameters and request bodies.
  • Commonly used in Spring Boot for building web services.

Que 29. How does Java’s Optional class help avoid NullPointerException, and how can it be used in a simple program?

Answer: The Optional class, introduced in Java 8, helps avoid NullPointerException by providing a wrapper for values that may or may not be present, encouraging explicit null handling.

How it works:

  • Optional.ofNullable: Creates an Optional that may hold a null value.
  • orElse: Provides a default value if the Optional is empty.
  • isPresent: Checks if a value exists before accessing it.

Example:

import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {
        String name = null;
        Optional<String> optionalName = Optional.ofNullable(name);
        String result = optionalName.orElse("Default Name");
        System.out.println(result); // Outputs: Default Name

        optionalName.ifPresent(n -> System.out.println("Name: " + n));
    }
}

Key points:

  • Prevents NullPointerException by forcing explicit null checks.
  • Simplifies code for freshers handling potentially null values.
  • Encourages functional programming with methods like map and filter.

Que 30. What is the purpose of the @ComponentScan annotation in Spring, and how does it help in discovering beans?

Answer: The @ComponentScan annotation in Spring tells the framework where to look for classes annotated with @Component, @Service, @Repository, or @Controller, automatically registering them as beans in the application context.

How it works:

  • Scans specified packages for annotated classes and creates beans.
  • Works with @Configuration to define the application context.
  • Reduces manual bean registration.

Example:

@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {
}

@Service
public class UserService {
    public String getUser() {
        return "User fetched";
    }
}

@Component
public class UserComponent {
    private final UserService userService;

    @Autowired
    public UserComponent(UserService userService) {
        this.userService = userService;
    }

    public String fetchUser() {
        return userService.getUser();
    }
}

Key points:

  • @ComponentScan simplifies bean discovery for freshers.
  • Default scanning starts from the package of the @Configuration class.
  • Use basePackages to specify custom package paths for scanning.
Java Interview Questions Freshers

Core Java Interview Questions for Freshers

Que 31. What is the purpose of the @Bean annotation in Spring, and how does it differ from @Component?

Answer: The @Bean annotation in Spring is used within a @Configuration class to define a Spring-managed bean programmatically, allowing fine-grained control over bean creation. In contrast, @Component is used to mark a class for automatic detection during component scanning.

Key differences:

  • @Bean: Defined in a @Configuration class, explicitly creates a bean via a method.
  • @Component: Automatically detected by @ComponentScan, no explicit method needed.
  • Use Case: Use @Bean for third-party classes or custom initialization; use @Component for application-specific classes.

Example:

@Configuration
public class AppConfig {
    @Bean
    public UserService userService() {
        return new UserService();
    }
}

@Component
public class UserService {
    public String getUser() {
        return "User fetched";
    }
}

Key points:

  • @Bean is ideal for configuring external libraries or complex bean setups.
  • Simplifies bean management for freshers learning Spring configuration.
  • @Component is more declarative and easier for simple use cases.

Que 32. How does the synchronized keyword in Java ensure thread safety, and what are its limitations?

Answer: The synchronized keyword in Java ensures thread safety by allowing only one thread to access a block of code or method at a time, preventing race conditions in multi-threaded environments.

How it works:

  • Synchronized Method: Locks the entire object (or class for static methods).
  • Synchronized Block: Locks a specific object, providing finer control.
  • Mutual Exclusion: Ensures only one thread executes the synchronized code.

Example:

public class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++; // Only one thread can execute at a time
    }

    public void incrementBlock() {
        synchronized (this) {
            count++; // Locks on the Counter instance
        }
    }

    public int getCount() {
        return count;
    }
}

Key points:

  • Prevents concurrent modification issues for shared resources.
  • Limitations: Can cause performance bottlenecks due to locking; not suitable for complex concurrency needs (use java.util.concurrent instead).
  • Easy for freshers to understand basic thread safety.

Que 33. What is the role of the @Repository annotation in Spring, and how does it support database operations?

Answer: The @Repository annotation in Spring marks a class as a Data Access Object (DAO), indicating it handles database operations. It is a specialization of @Component and provides additional features like exception translation.

Key features:

  • Exception Translation: Converts database-specific exceptions (e.g., SQLException) into Spring’s DataAccessException hierarchy.
  • Component Scanning: Automatically detected by @ComponentScan.
  • DAO Pattern: Encapsulates database access logic.

Example:

@Repository
public class UserRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public User findUserById(Long id) {
        String sql = "SELECT * FROM users WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{id}, (rs, rowNum) -> 
            new User(rs.getLong("id"), rs.getString("name")));
    }
}

public class User {
    private Long id;
    private String name;

    public User(Long id, String name) {
        this.id = id;
        this.name = name;
    }
    // Getters
}

Key points:

  • Simplifies database access for freshers using Spring Data or JdbcTemplate.
  • Enhances error handling with consistent exception types.
  • Commonly used in enterprise applications for data persistence.

Que 34. How does the Java Collections Framework support generics, and why is it beneficial for freshers?

Answer: The Java Collections Framework supports generics (introduced in Java 5) to provide type safety and eliminate the need for explicit casting when working with collections like List, Set, or Map.

How it works:

  • Generics specify the type of elements a collection can hold (e.g., List).
  • The compiler enforces type safety, preventing runtime errors.
  • Eliminates casting when retrieving elements.

Example:

import java.util.ArrayList;
import java.util.List;

public class GenericsDemo {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Alice");
        // names.add(123); // Compile-time error
        String name = names.get(0); // No casting needed
        System.out.println(name); // Outputs: Alice
    }
}

Key points:

  • Generics improve code readability and safety for freshers.
  • Prevents ClassCastException at runtime.
  • Widely used in modern Java applications for type-safe collections.

Que 35. What is the purpose of the @Service annotation in Spring, and how does it fit into a layered architecture?

Answer: The @Service annotation in Spring marks a class as a service-layer component, encapsulating business logic. It is a specialization of @Component, used to indicate the class’s role in a layered architecture.

Role in layered architecture:

  • Controller Layer: Handles HTTP requests (e.g., @RestController).
  • Service Layer: Contains business logic (@Service).
  • Repository Layer: Manages data access (@Repository).

Example:

@Service
public class OrderService {
    public String processOrder(String orderId) {
        return "Order " + orderId + " processed";
    }
}

@RestController
@RequestMapping("/api/orders")
public class OrderController {
    private final OrderService orderService;

    @Autowired
    public OrderController(OrderService orderService) {
        this.orderService = orderService;
    }

    @GetMapping("/{id}")
    public String getOrder(@PathVariable String id) {
        return orderService.processOrder(id);
    }
}

Key points:

  • @Service improves code readability by clearly defining the business logic layer.
  • Simplifies dependency injection for freshers building layered applications.
  • Promotes separation of concerns in Spring projects.

Que 36. How does Java’s ExecutorService simplify thread management, and how can it be used to run tasks?

Answer: The ExecutorService in Java (part of java.util.concurrent) simplifies thread management by providing a high-level API to execute tasks asynchronously, abstracting low-level thread creation and management.

Key features:

  • Thread Pool: Manages a pool of threads to execute tasks, reducing overhead.
  • Task Submission: Supports Runnable and Callable tasks.
  • Shutdown: Gracefully stops the executor when tasks are complete.

Example:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorDemo {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        executor.submit(() -> System.out.println("Task 1: " + Thread.currentThread().getName()));
        executor.submit(() -> System.out.println("Task 2: " + Thread.currentThread().getName()));
        executor.shutdown();
    }
}

Key points:

  • Simplifies multi-threading for freshers by hiding thread lifecycle management.
  • Supports fixed, cached, or single-threaded pools.
  • Ensures efficient resource usage in concurrent applications.

Que 37. What is the role of the @PathVariable annotation in Spring, and how is it used in REST APIs?

Answer: The @PathVariable annotation in Spring extracts values from the URL path of a REST API request, allowing dynamic handling of URL parameters.

How it works:

  • Maps URL segments to method parameters.
  • Commonly used in REST controllers to retrieve resource identifiers.

Example:

@RestController
@RequestMapping("/api/users")
public class UserController {
    @GetMapping("/{id}")
    public String getUser(@PathVariable Long id) {
        return "User ID: " + id;
    }

    @GetMapping("/{id}/profile/{name}")
    public String getProfile(@PathVariable Long id, @PathVariable String name) {
        return "Profile for user " + id + ": " + name;
    }
}

Key points:

  • Simplifies URL parameter handling for freshers building REST APIs.
  • Supports multiple path variables in a single request.
  • Use with @RequestMapping or @GetMapping for REST endpoints.

Que 38. How does Java’s lambda expressions simplify coding, and how can they be used with collections?

Answer: Lambda expressions, introduced in Java 8, simplify coding by providing a concise way to represent functional interfaces, enabling functional programming patterns.

Key benefits:

  • Conciseness: Replaces verbose anonymous classes.
  • Readability: Makes code cleaner, especially with collections.
  • Functional Interfaces: Works with interfaces like Runnable, Comparator, or Predicate.

Example with collections:

import java.util.*;
import java.util.stream.Collectors;

public class LambdaDemo {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
        // Filter even numbers using lambda
        List<Integer> evens = numbers.stream()
            .filter(n -> n % 2 == 0)
            .collect(Collectors.toList());
        System.out.println(evens); // Outputs: [2, 4]
    }
}

Key points:

  • Simplifies collection operations for freshers using Stream API.
  • Reduces boilerplate code compared to loops or anonymous classes.
  • Commonly used in modern Java for functional-style programming.

Que 39. What is the purpose of the @EnableAutoConfiguration annotation in Spring Boot, and how does it work?

Answer: The @EnableAutoConfiguration annotation in Spring Boot enables automatic configuration of the application context based on the dependencies present in the classpath, reducing manual configuration.

How it works:

  • Scans the classpath for libraries (e.g., spring-boot-starter-web, spring-boot-starter-data-jpa).
  • Configures beans automatically (e.g., DataSource for JPA, DispatcherServlet for web).
  • Part of @SpringBootApplication (which includes @EnableAutoConfiguration).

Example:

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

Key points:

  • Simplifies setup for freshers by auto-configuring common components.
  • Works with starters to include necessary dependencies.
  • Can be customized with exclude or excludeName to disable specific auto-configurations.

Que 40. How does Java’s ConcurrentHashMap differ from HashMap, and why is it useful for multi-threaded applications?

Answer: ConcurrentHashMap is a thread-safe version of HashMap in Java, designed for concurrent access in multi-threaded applications without requiring external synchronization.

Key differences:

  • Thread Safety: ConcurrentHashMap supports concurrent reads and writes; HashMap is not thread-safe.
  • Performance: Uses fine-grained locking (segmentation in Java 7, node-level locks in Java 8) for better concurrency.
  • Null Handling: ConcurrentHashMap does not allow null keys or values; HashMap does.

Example:

import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentMapDemo {
    public static void main(String[] args) {
        ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
        map.put("Alice", 25);
        map.put("Bob", 30);

        // Concurrent access
        new Thread(() -> map.put("Charlie", 35)).start();
        new Thread(() -> System.out.println(map.get("Alice"))).start();
    }
}

Key points:

  • Simplifies concurrent programming for freshers by avoiding explicit locks.
  • Ideal for shared data in multi-threaded applications.
  • Provides high performance with concurrent read/write operations.

Que 41. What is the purpose of the @Qualifier annotation in Spring, and how does it resolve dependency injection ambiguity?

Answer: The @Qualifier annotation in Spring is used to resolve ambiguity when multiple beans of the same type are available for dependency injection. It specifies which bean to inject by name, ensuring the correct dependency is selected.

How it works:

  • Used alongside @Autowired to specify the bean name.
  • Resolves conflicts when Spring cannot determine which bean to inject based on type alone.

Example:

@Component("emailService")
public class EmailService {
    public String sendMessage() {
        return "Email sent";
    }
}

@Component("smsService")
public class SmsService {
    public String sendMessage() {
        return "SMS sent";
    }
}

@RestController
public class NotificationController {
    private final EmailService emailService;
    private final SmsService smsService;

    @Autowired
    public NotificationController(@Qualifier("emailService") EmailService emailService,
                                  @Qualifier("smsService") SmsService smsService) {
        this.emailService = emailService;
        this.smsService = smsService;
    }

    public String notifyUser() {
        return emailService.sendMessage() + ", " + smsService.sendMessage();
    }
}

Key points:

  • @Qualifier ensures precise bean selection for freshers working with multiple implementations.
  • Commonly used with interfaces or abstract classes having multiple implementations.
  • Simplifies dependency injection in complex Spring applications.

Que 42. How does Java’s Runnable interface work, and how can it be used to create threads?

Answer: The Runnable interface in Java defines a single method, run(), to specify a task that can be executed by a thread. It is used to create threads by passing a Runnable instance to a Thread object or an ExecutorService.

How it works:

  • Implement the run() method to define the task logic.
  • Pass the Runnable to a Thread or ExecutorService for execution.

Example:

public class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("Running in thread: " + Thread.currentThread().getName());
    }
}

class ThreadDemo {
    public static void main(String[] args) {
        MyRunnable task = new MyRunnable();
        Thread thread = new Thread(task);
        thread.start(); // Starts the thread
    }
}

Key points:

  • Runnable separates task logic from thread management, making it reusable.
  • Preferred over extending Thread for better flexibility.
  • Easy for freshers to understand basic multi-threading concepts.

Que 43. What is the role of the @RequestBody annotation in Spring, and how is it used in REST APIs?

Answer: The @RequestBody annotation in Spring maps the body of an HTTP request to a method parameter, typically for POST or PUT requests in REST APIs. It deserializes JSON or XML into a Java object.

How it works:

  • Reads the request body and converts it to the specified parameter type.
  • Commonly used with @PostMapping or @PutMapping to process client data.

Example:

@RestController
@RequestMapping("/api/users")
public class UserController {
    @PostMapping
    public String createUser(@RequestBody User user) {
        return "Created user: " + user.getName();
    }
}

public class User {
    private String name;
    // Getters, setters
}

Key points:

  • Simplifies handling JSON/XML payloads for freshers building REST APIs.
  • Requires a JSON library (e.g., Jackson) in the classpath.
  • Validates input using @Valid for data integrity.

Que 44. How does Java’s ArrayList differ from LinkedList, and when should each be used?

Answer: ArrayList and LinkedList are two implementations of the List interface in Java, differing in their internal structure and performance characteristics.

FeatureArrayListLinkedList
StructureDynamic arrayDoubly-linked list
Get/Set PerformanceO(1) for random accessO(n) for random access
Insert/DeleteO(n) (requires shifting)O(1) at head/tail, O(n) in middle
Memory UsageLess overheadMore overhead (node pointers)

Example:

import java.util.*;

public class ListDemo {
    public static void main(String[] args) {
        List<String> arrayList = new ArrayList<>();
        arrayList.add("Alice");
        System.out.println(arrayList.get(0)); // Fast access: Alice

        List<String> linkedList = new LinkedList<>();
        linkedList.addFirst("Bob"); // Fast insertion
        System.out.println(linkedList.get(0)); // Slower access: Bob
    }
}

Key points:

  • Use ArrayList for frequent random access or iteration.
  • Use LinkedList for frequent insertions/deletions at the ends.
  • Helps freshers choose the right List implementation for their use case.

Que 45. What is the purpose of the @SpringBootApplication annotation, and what does it include?

Answer: The @SpringBootApplication annotation in Spring Boot is a convenience annotation that combines three annotations: @Configuration, @EnableAutoConfiguration, and @ComponentScan. It serves as the entry point for a Spring Boot application.

Components:

  • @Configuration: Marks the class as a source of bean definitions.
  • @EnableAutoConfiguration: Enables auto-configuration of beans based on classpath dependencies.
  • @ComponentScan: Scans for components (e.g., @Component, @Service) in the specified package.

Example:

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

Key points:

  • Simplifies Spring Boot setup for freshers by combining essential annotations.
  • Automatically configures components like web servers or databases.
  • Defines the main class for running the application.

Que 46. How does Java’s Thread class differ from the Runnable interface, and why is Runnable preferred?

Answer: Java’s Thread class and Runnable interface both enable multi-threading, but they differ in their design and usage.

FeatureThread ClassRunnable Interface
DefinitionExtends Thread to define a threadImplements Runnable for task logic
FlexibilityTies task to threadSeparates task from thread
InheritanceUses single inheritanceAllows class to extend another
ReusabilityLess reusableHighly reusable

Example using Runnable:

public class MyTask implements Runnable {
    @Override
    public void run() {
        System.out.println("Task running");
    }
}

class ThreadDemo {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyTask());
        thread.start();
    }
}

Key points:

  • Runnable is preferred for its flexibility and reusability.
  • Allows freshers to separate task logic from thread management.
  • Supports use with ExecutorService for thread pooling.

Que 47. What is the role of the JdbcTemplate in Spring, and how does it simplify database operations?

Answer: The JdbcTemplate class in Spring simplifies database operations by providing a high-level API for executing SQL queries, reducing boilerplate code for JDBC operations.

Key features:

  • Simplified Queries: Executes SQL queries and maps results to objects.
  • Exception Handling: Translates SQLException to Spring’s DataAccessException.
  • Connection Management: Handles connection lifecycle automatically.

Example:

@Repository
public class UserRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public User findById(Long id) {
        String sql = "SELECT * FROM users WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{id}, (rs, rowNum) ->
            new User(rs.getLong("id"), rs.getString("name")));
    }
}

public class User {
    private Long id;
    private String name;

    public User(Long id, String name) {
        this.id = id;
        this.name = name;
    }
    // Getters
}

Key points:

  • Reduces JDBC boilerplate for freshers (e.g., no manual connection closing).
  • Supports parameterized queries to prevent SQL injection.
  • Integrates with Spring’s transaction management.

Que 48. How does Java’s forEach method work with collections, and how can it be used with lambda expressions?

Answer: The forEach method, introduced in Java 8, is a default method in the Iterable interface that allows iterating over a collection and applying an action to each element, often using lambda expressions for concise code.

How it works:

  • Accepts a Consumer functional interface to process each element.
  • Simplifies iteration compared to traditional for loops.

Example:

import java.util.Arrays;
import java.util.List;

public class ForEachDemo {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
        names.forEach(name -> System.out.println("Name: " + name));
    }
}

Key points:

  • Simplifies iteration for freshers using functional programming.
  • Works with any collection (e.g., List, Set).
  • Enhances readability with lambda expressions.

Que 49. What is the purpose of the @Value annotation in Spring, and how is it used to inject properties?

Answer: The @Value annotation in Spring injects values from configuration sources (e.g., application.properties or YAML files) into fields, methods, or constructor parameters.

How it works:

  • Reads values from properties files using placeholders (e.g., ${property.key}).
  • Supports default values if the property is not found.

Example:

// application.properties
app.name=MyApp
app.version=1.0

@Service
public class AppService {
    @Value("${app.name}")
    private String appName;

    @Value("${app.version:Unknown}")
    private String appVersion;

    public String getAppInfo() {
        return appName + " v" + appVersion;
    }
}

Key points:

  • Simplifies configuration management for freshers.
  • Supports environment variables and SpEL (Spring Expression Language).
  • Commonly used for externalizing application settings.

Que 50. How does Java’s StringBuilder class improve performance compared to String, and when should it be used?

Answer: The StringBuilder class in Java provides a mutable alternative to the immutable String class, improving performance for string manipulations like concatenation in loops.

Key differences:

  • String: Immutable, creating a new object for each modification.
  • StringBuilder: Mutable, modifies the same object, reducing memory overhead.

Example:

public class StringBuilderDemo {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 100; i++) {
            sb.append(i); // Efficient, modifies same object
        }
        System.out.println(sb.toString());
    }
}

Key points:

  • Use StringBuilder for frequent string modifications (e.g., loops).
  • More efficient than String concatenation for performance.
  • Easy for freshers to use in scenarios requiring dynamic string building.
Java Selenium Interview QuestionsJava OOPs Interview Questions
Top Coding Interview QuestionsFull Stack Developer Interview Questions
Java Interview Questions for ExperiencedBack End Developer Interview Questions

Similar Posts

Leave a Reply

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