core java engineer Interview Questions and Answers

100 Core Java Interview Questions and Answers
  1. What is Java?

    • Answer: Java is a high-level, class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. It's known for its platform independence ("write once, run anywhere"), achieved through the use of the Java Virtual Machine (JVM).
  2. What is the difference between JDK, JRE, and JVM?

    • Answer: The JDK (Java Development Kit) is a complete package including the JRE, compiler, debugger, and other development tools. The JRE (Java Runtime Environment) contains the JVM, class libraries, and other components necessary to run Java applications. The JVM (Java Virtual Machine) is the runtime engine that executes Java bytecode.
  3. Explain the concept of Object-Oriented Programming (OOP).

    • Answer: OOP is a programming paradigm based on the concept of "objects," which contain data (fields) and code (methods) that operate on that data. Key principles include encapsulation, inheritance, polymorphism, and abstraction.
  4. What are the four fundamental principles of OOP?

    • Answer: Encapsulation (hiding internal data and methods), Inheritance (creating new classes from existing ones), Polymorphism (objects taking on many forms), and Abstraction (showing only essential information and hiding complexity).
  5. What is the difference between `==` and `.equals()`?

    • Answer: `==` compares object references (memory addresses), while `.equals()` compares the content of objects. For primitive types, `==` compares values. You must override `.equals()` to provide meaningful content comparison for custom classes.
  6. Explain the concept of inheritance in Java.

    • Answer: Inheritance allows a class (subclass or child class) to inherit properties and methods from another class (superclass or parent class). It promotes code reusability and establishes an "is-a" relationship between classes.
  7. What are access modifiers in Java?

    • Answer: Access modifiers control the accessibility of classes, methods, and variables. They include `public`, `protected`, `private`, and (implicitly) default (package-private).
  8. What is polymorphism? Give an example.

    • Answer: Polymorphism allows objects of different classes to respond to the same method call in their own specific way. For example, a `Animal` class with a `makeSound()` method, and subclasses like `Dog` and `Cat` overriding `makeSound()` to produce different sounds.
  9. What is method overriding?

    • Answer: Method overriding is when a subclass provides a specific implementation for a method that is already defined in its superclass. It's a key aspect of polymorphism.
  10. What is method overloading?

    • Answer: Method overloading is having multiple methods with the same name in the same class, but with different parameters (number, type, or order).
  11. What is an abstract class?

    • Answer: An abstract class cannot be instantiated directly; it serves as a blueprint for subclasses. It can contain abstract methods (methods without implementation) that must be implemented by subclasses.
  12. What is an interface?

    • Answer: An interface is a completely abstract class that contains only constants and abstract methods. Classes implement interfaces, promising to provide implementations for all methods declared in the interface. Java allows multiple interface inheritance.
  13. What is the difference between an abstract class and an interface?

    • Answer: An abstract class can have both abstract and concrete methods, while an interface can only have abstract methods (and constants). A class can extend only one abstract class but implement multiple interfaces.
  14. Explain the concept of exception handling in Java.

    • Answer: Exception handling is a mechanism to manage runtime errors. It uses `try`, `catch`, and `finally` blocks to handle exceptions gracefully, preventing program crashes.
  15. What are checked and unchecked exceptions?

    • Answer: Checked exceptions are exceptions that the compiler forces you to handle (e.g., `IOException`). Unchecked exceptions are runtime exceptions that don't require explicit handling (e.g., `NullPointerException`, `ArrayIndexOutOfBoundsException`).
  16. What is a `finally` block?

    • Answer: The `finally` block is always executed, regardless of whether an exception is thrown or caught. It's typically used for cleanup tasks (like closing files or releasing resources).
  17. What is the difference between `throw` and `throws` keywords?

    • Answer: `throw` is used to explicitly throw an exception. `throws` is used in a method signature to declare that the method might throw an exception (it doesn't handle it).
  18. What is a custom exception?

    • Answer: A custom exception is a user-defined exception class that extends either the `Exception` class or the `RuntimeException` class. It allows developers to create specific exceptions for their application's needs.
  19. Explain the concept of multithreading in Java.

    • Answer: Multithreading allows multiple threads to execute concurrently within a single program. It improves performance by utilizing multiple CPU cores and enhances responsiveness.
  20. How do you create a thread in Java?

    • Answer: You can create a thread by extending the `Thread` class or implementing the `Runnable` interface.
  21. Explain the difference between `start()` and `run()` methods.

    • Answer: `start()` initiates a new thread and calls `run()`. Calling `run()` directly executes the code in the current thread, not a new one.
  22. What is thread synchronization?

    • Answer: Thread synchronization is a mechanism to control access to shared resources among multiple threads, preventing race conditions and data corruption. It's often achieved using `synchronized` blocks or methods.
  23. What is deadlock?

    • Answer: Deadlock occurs when two or more threads are blocked indefinitely, waiting for each other to release resources that they need.
  24. What is a collection in Java?

    • Answer: A collection is a framework that provides ways to store and manipulate groups of objects. It includes interfaces like `List`, `Set`, `Queue`, and `Map`, and concrete implementations like `ArrayList`, `HashSet`, `LinkedList`, etc.
  25. What is the difference between `ArrayList` and `LinkedList`?

    • Answer: `ArrayList` uses a dynamic array, providing fast random access but slower insertions/deletions. `LinkedList` uses a doubly linked list, offering fast insertions/deletions but slower random access.
  26. What is a HashMap?

    • Answer: A `HashMap` is an implementation of the `Map` interface. It stores data in key-value pairs, allowing fast access to values using their keys. It does not guarantee the order of elements.
  27. What is a HashSet?

    • Answer: A `HashSet` is an implementation of the `Set` interface. It stores unique elements and does not guarantee the order of elements. It uses a hash table for fast lookups.
  28. What is the difference between HashMap and TreeMap?

    • Answer: `HashMap` does not guarantee order, while `TreeMap` maintains elements in a sorted order (based on keys).
  29. What is generics in Java?

    • Answer: Generics allow you to write type-safe code by parameterizing types. It avoids type casting and improves code readability and maintainability.
  30. Explain autoboxing and unboxing.

    • Answer: Autoboxing is the automatic conversion of a primitive type to its corresponding wrapper class (e.g., `int` to `Integer`). Unboxing is the reverse process.
  31. What is a Wrapper class?

    • Answer: Wrapper classes provide a way to treat primitive types as objects. For each primitive type (e.g., `int`, `boolean`), there is a corresponding wrapper class (e.g., `Integer`, `Boolean`).
  32. What is serialization in Java?

    • Answer: Serialization is the process of converting an object into a byte stream, allowing it to be stored in a file or transmitted over a network. The `Serializable` interface is used for this purpose.
  33. What is deserialization in Java?

    • Answer: Deserialization is the reverse process of serialization: reconstructing an object from a byte stream.
  34. What is the purpose of the `transient` keyword?

    • Answer: The `transient` keyword prevents a field from being serialized. It's used for fields that should not be persisted.
  35. What is an inner class?

    • Answer: An inner class is a class defined inside another class. It can access members of the outer class.
  36. What are the different types of inner classes?

    • Answer: Member inner class, static nested class, local inner class, anonymous inner class.
  37. What is the difference between static nested class and inner class?

    • Answer: A static nested class does not have access to members of the outer class unless they are static. An inner class has implicit access to members of the outer class.
  38. What is the Java Memory Model (JMM)?

    • Answer: The JMM defines how threads interact with the memory system. It specifies rules for how threads read and write to memory, ensuring data consistency and preventing race conditions.
  39. What is garbage collection in Java?

    • Answer: Garbage collection is the automatic process of reclaiming memory occupied by objects that are no longer referenced by the program.
  40. What is the difference between `System.gc()` and `Runtime.getRuntime().gc()`?

    • Answer: Both suggest garbage collection, but there's no guarantee it will be run immediately. `Runtime.getRuntime().gc()` is generally preferred.
  41. What is a String in Java?

    • Answer: A `String` is an immutable sequence of characters. Once a `String` object is created, its value cannot be changed.
  42. What is the difference between `String`, `StringBuffer`, and `StringBuilder`?

    • Answer: `String` is immutable, `StringBuffer` is mutable and synchronized (thread-safe), and `StringBuilder` is mutable and not synchronized (faster for single-threaded applications).
  43. What is a design pattern?

    • Answer: A design pattern is a reusable solution to a commonly occurring problem within a given context in software design. They are not finished code, but templates for solutions.
  44. Name some common design patterns.

    • Answer: Singleton, Factory, Observer, Strategy, Decorator, Template Method.
  45. What is the Singleton design pattern?

    • Answer: The Singleton pattern restricts the instantiation of a class to one "single" instance. This is useful for classes representing resources that should be unique (e.g., a database connection).
  46. What is the Factory design pattern?

    • Answer: The Factory pattern provides an interface for creating objects without specifying their concrete classes. This makes the code more flexible and easier to maintain.
  47. What is JDBC?

    • Answer: JDBC (Java Database Connectivity) is an API for connecting Java applications to relational databases.
  48. Explain the steps involved in connecting to a database using JDBC.

    • Answer: Load the JDBC driver, establish a connection, create a statement object, execute queries, process results, close the connection.
  49. What is prepared statement in JDBC?

    • Answer: A prepared statement is a pre-compiled SQL statement that can be executed multiple times with different parameters, improving performance and security.
  50. What is a stored procedure?

    • Answer: A stored procedure is a pre-compiled SQL code block that resides in the database. It can be called from a Java application or other database clients.
  51. What are annotations in Java?

    • Answer: Annotations are metadata that provide information about the code. They are used for various purposes, including code documentation, compile-time checks, and runtime processing.
  52. What are some common annotations in Java?

    • Answer: `@Override`, `@Deprecated`, `@SuppressWarnings`, `@Nullable`, `@NonNull`.
  53. What is reflection in Java?

    • Answer: Reflection is the ability of a program to inspect and modify its own structure and behavior at runtime. It allows you to access and manipulate classes, methods, and fields dynamically.
  54. What is Java Stream API?

    • Answer: The Java Stream API provides a functional approach to processing collections of data. It allows for concise and efficient operations on data.
  55. Explain Lambda expressions in Java.

    • Answer: Lambda expressions are anonymous functions that can be passed as arguments to methods or assigned to variables. They are a key part of functional programming in Java.
  56. What is a functional interface?

    • Answer: A functional interface is an interface that contains exactly one abstract method. It can have multiple default methods and static methods.
  57. What is method reference in Java?

    • Answer: A method reference provides a concise way to refer to an existing method without explicitly writing a lambda expression. It uses the `::` operator.
  58. What is JavaFX?

    • Answer: JavaFX is a set of graphics and media packages that allows developers to create rich client applications with a modern look and feel.
  59. What is Spring Framework?

    • Answer: Spring is a popular Java application framework that provides comprehensive infrastructure support for developing Java applications.
  60. What is dependency injection?

    • Answer: Dependency injection is a design pattern where dependencies are provided to a class instead of the class creating them itself. Spring Framework heavily uses this pattern.
  61. What is IoC container in Spring?

    • Answer: The IoC (Inversion of Control) container in Spring is responsible for managing the creation and configuration of objects (beans) in an application.
  62. Explain different types of dependency injection in Spring.

    • Answer: Constructor injection, setter injection, field injection.
  63. What is aspect-oriented programming (AOP)?

    • Answer: AOP is a programming paradigm that separates cross-cutting concerns (like logging or security) from the core business logic. Spring provides AOP capabilities.
  64. What is Spring Boot?

    • Answer: Spring Boot simplifies the development of Spring applications by providing auto-configuration, starter dependencies, and embedded servers.
  65. What is RESTful API?

    • Answer: A RESTful API (Representational State Transfer) is an architectural style for building web services using HTTP methods (GET, POST, PUT, DELETE) to interact with resources.
  66. Explain the concept of REST controllers in Spring Boot.

    • Answer: REST controllers in Spring Boot are used to handle HTTP requests and return responses in a RESTful manner. They use annotations like `@GetMapping`, `@PostMapping`, etc.
  67. What is Hibernate?

    • Answer: Hibernate is an Object-Relational Mapping (ORM) framework that simplifies database interaction in Java applications.
  68. What are JPA and Hibernate's relationship?

    • Answer: JPA (Java Persistence API) is a specification, and Hibernate is a popular implementation of JPA. Hibernate provides features beyond the JPA specification.
  69. Explain different types of relationships in Hibernate.

    • Answer: One-to-one, one-to-many, many-to-one, many-to-many.
  70. What is the role of a SessionFactory in Hibernate?

    • Answer: The SessionFactory is a thread-safe object that acts as a factory for creating `Session` objects. It is responsible for managing connections to the database.
  71. What is a Session in Hibernate?

    • Answer: A Session is a non-thread-safe object that is used to interact with the database. It provides methods for saving, updating, deleting, and retrieving objects.
  72. What is Maven?

    • Answer: Maven is a build automation tool used for managing project dependencies and building Java projects. It uses a project object model (POM) to define project structure and dependencies.
  73. What is a POM file?

    • Answer: A POM (Project Object Model) file is an XML file that describes a Maven project. It contains information about the project's dependencies, plugins, and other configurations.
  74. What is Gradle?

    • Answer: Gradle is another popular build automation tool for Java and other languages, offering more flexibility and performance compared to Maven in some scenarios.
  75. What is the difference between Maven and Gradle?

    • Answer: Gradle uses a Groovy-based DSL (Domain Specific Language), while Maven uses XML. Gradle generally offers more flexibility and performance for larger projects.
  76. Explain different ways to handle concurrency in Java.

    • Answer: Using `synchronized` blocks/methods, using locks (e.g., `ReentrantLock`), using concurrent collections (e.g., `ConcurrentHashMap`), using thread pools.
  77. What are the different states of a thread?

    • Answer: New, Runnable, Running, Blocked, Waiting, Timed Waiting, Terminated.
  78. What is a thread pool?

    • Answer: A thread pool is a collection of worker threads that are reused to execute tasks, reducing the overhead of creating and destroying threads.
  79. Explain the use of ExecutorService in Java.

    • Answer: `ExecutorService` is an interface that provides methods for managing a thread pool. It simplifies the process of submitting tasks and managing threads.
  80. What is Java 8's Optional class?

    • Answer: The `Optional` class is a container object that may or may not contain a non-null value. It helps to handle situations where a value might be absent, preventing `NullPointerExceptions`.
  81. What are streams in Java 8?

    • Answer: Streams are a powerful feature in Java 8 that provide a declarative way to process collections of data. They support functional operations like filtering, mapping, and reducing.
  82. Explain different types of stream operations in Java 8.

    • Answer: Intermediate operations (e.g., `filter`, `map`, `sorted`) and terminal operations (e.g., `collect`, `forEach`, `reduce`).
  83. What is the difference between parallel streams and sequential streams?

    • Answer: Sequential streams process elements one by one, while parallel streams process elements concurrently using multiple threads. Parallel streams can improve performance for large datasets.
  84. Explain the concept of immutability in Java.

    • Answer: Immutability means that once an object is created, its state cannot be changed. This improves thread safety and simplifies concurrent programming.
  85. How to create an immutable class in Java?

    • Answer: Make all fields final, don't provide setter methods, make a defensive copy of mutable fields in the constructor.
  86. What is the difference between shallow copy and deep copy?

    • Answer: A shallow copy creates a new object, but it shares references to the original object's mutable fields. A deep copy creates a new object with independent copies of all fields, including nested objects.

Thank you for reading our blog post on 'core java engineer Interview Questions and Answers'.We hope you found it informative and useful.Stay tuned for more insightful content!