1. What is the difference between JDK, JRE, and JVM?
Answer: JDK (Java Development Kit) is a software development kit used to develop Java applications. JRE (Java Runtime Environment) provides the libraries, Java Virtual Machine (JVM), and other components to run applications written in Java. JVM is an abstract machine that enables your computer to run a Java program.
2. Explain the concept of Object-Oriented Programming in Java.
Answer: OOP is a programming paradigm based on the concept of "objects", which can contain data and code. The four main principles are encapsulation, inheritance, polymorphism, and abstraction.
3. How does Java achieve memory management?
Answer: Java achieves memory management through a garbage collector that automatically deallocates memory by removing objects that are no longer referenced by the program. This helps in preventing memory leaks and optimizing available memory.
4. What are Java Collections, and can you explain some commonly used collections?
Answer: Java Collections is a framework that provides an architecture to store and manipulate a group of objects. Some commonly used collections include ArrayList, LinkedList, HashSet, TreeSet, HashMap, and TreeMap.
5. Explain method overloading and method overriding with examples.
Answer: Method overloading occurs when multiple methods in the same class have the same name but different parameters. Method overriding occurs when a subclass has a method with the same name and parameters as a method in its superclass.
Example of Overloading:
java
Copy code
public class MathUtils {
public int add(int a, int b) { return a + b; }
public double add(double a, double b) { return a + b; }
}
Example of Overriding:
java
Copy code
class Animal {
void sound() { System.out.println("Animal makes a sound"); }
}
class Dog extends Animal {
void sound() { System.out.println("Dog barks"); }
}
6. Write a Java program to implement a binary search algorithm.
Answer:
java
Copy code
public class BinarySearch {
public int binarySearch(int[] arr, int key) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == key) return mid;
if (arr[mid] < key) left = mid + 1;
else right = mid - 1;
}
return -1;
}
public static void main(String[] args) {
BinarySearch bs = new BinarySearch();
int[] arr = {1, 2, 3, 4, 5};
int result = bs.binarySearch(arr, 3);
System.out.println(result);
}
}
7. Describe how a HashMap works in Java.
Answer: A HashMap in Java uses an array of buckets where each bucket corresponds to a hash code of the key. It uses the hashCode() method to determine the bucket and the equals() method to find the correct key-value pair in the bucket. It allows null keys and values and provides constant-time performance for basic operations like get and put, assuming the hash function disperses the elements properly among the buckets.
8. What are functional interfaces in Java 8?
Answer: Functional interfaces are interfaces with a single abstract method, used as the basis for lambda expressions and method references in Java 8. Examples include Runnable, Callable, Predicate, Function, and Consumer.
9. How do Streams work in Java 8?
Answer: Streams in Java 8 provide a sequence of elements from a source, supporting sequential and parallel aggregate operations. They enable functional-style operations on collections of objects, such as map, filter, and reduce, without modifying the underlying data source.
10. What are the differences between synchronized and volatile keywords in Java?
Answer: The synchronized keyword ensures that only one thread can execute a block of code or method at a time, providing mutual exclusion and visibility guarantees. The volatile keyword ensures that the value of a variable is always read from and written to the main memory, providing visibility guarantees but not mutual exclusion.
11. What is the Spring Bean lifecycle?
Answer: The Spring Bean lifecycle includes several phases:
Instantiation: The container creates an instance of the bean.
Populating properties: Dependencies are injected.
BeanNameAware and BeanFactoryAware interfaces: If the bean implements these interfaces, the corresponding methods are called.
Pre-initialization: BeanPostProcessor pre-initialization methods.
Initialization: InitializingBean's afterPropertiesSet method or a custom init method.
Post-initialization: BeanPostProcessor post-initialization methods.
Destruction: DisposableBean's destroy method or a custom destroy method.
12. Explain how Hibernate handles the first and second level caches.
Answer: Hibernate's first level cache is the session cache, which is enabled by default and exists for the duration of the session. It stores objects being read or written during the session. The second level cache is session factory-scoped and is shared among all sessions, used to reduce database access for entities that are read frequently.
13. What is the Factory pattern, and where would you use it?
Answer: The Factory pattern is a creational design pattern that uses a factory method to create objects. It allows a class to delegate the responsibility of object instantiation to its subclasses. It is used when the exact type of object required may vary, and you want to hide the instantiation logic.
14. What is the Singleton pattern?
Answer: The Singleton pattern is a design pattern that ensures a class has only one instance and provides a global point of access to it. This is typically used for managing shared resources like configuration settings or database connections.
15. How does Java handle exceptions?
Answer: Java handles exceptions through a mechanism that uses try, catch, finally, and throw clauses. Exceptions can be caught and handled to prevent the program from crashing. Custom exceptions can be created by extending the Exception class.
16. Explain the concept of inheritance in Java.
Answer: Inheritance is an OOP principle where a new class (subclass) inherits attributes and behaviors (methods) from an existing class (superclass). It allows code reusability and the creation of hierarchical class structures.
17. What are abstract classes and interfaces in Java?
Answer: Abstract classes are classes that cannot be instantiated on their own and can have both abstract (without implementation) and concrete (with implementation) methods. Interfaces are contracts that define a set of abstract methods that implementing classes must override. Java 8 introduced default methods in interfaces.
18. How does Java handle multithreading?
Answer: Java handles multithreading through the Thread class and the Runnable interface. The synchronized keyword, wait(), notify(), and notifyAll() methods are used for thread communication and synchronization.
19. What are lambda expressions in Java 8?
Answer: Lambda expressions provide a clear and concise way to represent a method interface using an expression. They are used primarily to define the inline implementation of a functional interface.
Example:
java
Copy code
Comparator
comparator = (s1, s2) -> s1.compareTo(s2);
20. How does garbage collection work in Java?
Answer: Garbage collection in Java is the process of automatically identifying and disposing of objects that are no longer in use to free up memory. The JVM's garbage collector uses algorithms like Mark-and-Sweep, Generational, and G1 to manage memory efficiently.
21. What is a Java Stream, and how is it different from InputStream/OutputStream?
Answer: A Java Stream (introduced in Java 8) is a sequence of elements supporting aggregate operations. It is different from InputStream/OutputStream which are used for byte-based I/O operations. Java Streams enable functional programming with operations like map, filter, and reduce.
22. Explain the difference between == and equals() in Java.
Answer: == is a reference comparison operator used to check if two references point to the same object in memory. equals() is a method used to compare the content of two objects for logical equality.
23. What is the difference between ArrayList and LinkedList?
Answer: ArrayList is a resizable array implementation of the List interface, providing fast random access and slow insertions/removals in the middle. LinkedList is a doubly-linked list implementation, providing fast insertions/removals and slower random access.
24. Describe how you can implement a thread-safe singleton in Java.
Answer:
java
Copy code
public class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
25. How does the HashCode and Equals method work together in Java?
Answer: hashCode() returns an integer representation of the object, used in hashing-based collections like HashMap. equals() checks logical equality. Both methods must be overridden consistently to ensure that equal objects have the same hash code.
26. What is the difference between checked and unchecked exceptions?
Answer: Checked exceptions are checked at compile-time, and the method must handle them using try-catch or throws. Unchecked exceptions (runtime exceptions) are checked at runtime and don't require explicit handling.
27. How does the try-with-resources statement work?
Answer: The try-with-resources statement automatically closes resources like files and database connections when the1. What is the difference between JDK, JRE, and JVM?
Answer: JDK (Java Development Kit) is a software development kit used to develop Java applications. JRE (Java Runtime Environment) provides the libraries, Java Virtual Machine (JVM), and other components to run applications written in Java. JVM is an abstract machine that enables your computer to run a Java program.