1. What is the difference between `==` and `equals()` in Java?
`==` compares references (memory location), while `equals()` compares actual object values for equality. Use `equals()` for content comparison and `==` for reference comparison.
2. What is the purpose of the `final` keyword in Java?
The `final` keyword is used to define constants, prevent method overriding, and prevent class inheritance. A `final` variable cannot be reassigned, a `final` method cannot be overridden, and a `final` class cannot be subclassed.
3. What is the difference between an `ArrayList` and a `LinkedList`?
`ArrayList` is backed by a dynamic array, while `LinkedList` is backed by a doubly linked list. `ArrayList` provides fast random access but slower insertions and deletions, while `LinkedList` provides fast insertions and deletions but slower access times.
4. Explain the concept of Java’s pass-by-value mechanism.
Java is strictly pass-by-value. When passing primitive types, the actual value is passed, while when passing objects, the reference to the object is passed, but the reference itself is passed by value.
5. What is the difference between `ArrayList` and `Vector` in Java?
`ArrayList` is not synchronized, and it is faster than `Vector`, which is synchronized. `ArrayList` grows dynamically as needed, whereas `Vector` doubles its size when full.
6. What is the difference between `StringBuilder` and `StringBuffer`?
Both `StringBuilder` and `StringBuffer` are used to create mutable strings, but `StringBuffer` is synchronized, which makes it thread-safe but slower compared to `StringBuilder`, which is not synchronized and thus faster in single-threaded scenarios.
7. What is an interface in Java?
An interface in Java is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields or constructors.
8. What is the difference between `interface` and `abstract class` in Java?
An interface cannot have any method implementation, while an abstract class can have both abstract methods and method implementations. An abstract class can have instance fields, whereas an interface can only have constants.
9. What is method overloading in Java?
Method overloading occurs when two or more methods in the same class have the same name but differ in parameters (number, type, or both). It is resolved at compile-time.
10. What is method overriding in Java?
Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. The method signature in the subclass must match the one in the superclass, and overriding is resolved at runtime.
11. What is `super` keyword in Java?
`super` is used to refer to the immediate parent class of a class. It can be used to call parent class constructors, methods, and access parent class fields.
12. Explain the concept of exception handling in Java.
Exception handling in Java is managed using `try`, `catch`, `finally`, and `throw` keywords. Exceptions are events that disrupt the normal flow of a program. The `try` block contains code that may throw an exception, and the `catch` block handles it. The `finally` block executes after the `try` and `catch` blocks, regardless of whether an exception was thrown.
13. What is the difference between `checked` and `unchecked` exceptions in Java?
Checked exceptions are exceptions that must be either caught or declared in the method signature, such as `IOException`. Unchecked exceptions are runtime exceptions that do not need to be explicitly handled, such as `NullPointerException`.
14. What is the purpose of the `finally` block in Java?
The `finally` block is used to execute code that must run regardless of whether an exception was thrown or not. It is commonly used for resource cleanup, such as closing files or releasing database connections.
15. Explain the concept of multithreading in Java.
Multithreading is a Java feature that allows concurrent execution of two or more threads. Each thread runs in its own path of execution, and multithreading is used to improve the performance of CPU-bound and I/O-bound tasks.
16. What is synchronization in Java?
Synchronization is a process in Java that ensures that only one thread can access a resource at a time, preventing data corruption when multiple threads access shared data. It can be done using the `synchronized` keyword.
17. What is a deadlock in Java?
A deadlock occurs when two or more threads are blocked forever, waiting for each other to release resources. This happens when multiple threads hold locks and wait for each other’s locks.
18. What is the purpose of the `volatile` keyword in Java?
The `volatile` keyword ensures that the value of a variable is always read from and written to the main memory, ensuring visibility of changes across different threads.
19. What are the differences between `String`, `StringBuilder`, and `StringBuffer`?
`String` is immutable, meaning its value cannot be changed after it is created. `StringBuilder` and `StringBuffer` are mutable, meaning their values can be modified. `StringBuffer` is synchronized, making it thread-safe, while `StringBuilder` is not.
20. What is the `hashCode()` method in Java?
The `hashCode()` method returns an integer representation of the object’s memory address, used by hash-based collections like `HashMap` and `HashSet` for quick lookups.
21. What is the difference between `ArrayList` and `LinkedList` in Java?
`ArrayList` is backed by a dynamic array, which provides fast random access but slower insertion/deletion operations. `LinkedList` is backed by a doubly linked list, making insertions and deletions faster, but it has slower access times compared to `ArrayList`.
22. What is the difference between `final`, `finally`, and `finalize` in Java?
`final` is used to declare constants, prevent method overriding, and prevent class inheritance. `finally` is a block used in exception handling to ensure execution of code after `try` and `catch` blocks. `finalize` is a method in the `Object` class, which is called before an object is garbage collected.
23. What is the `super()` keyword in Java?
`super()` is used to call the constructor of the immediate parent class. It must be the first statement in the subclass constructor.
24. What is the difference between `throw` and `throws` in Java?
`throw` is used to explicitly throw an exception from within a method or block of code. `throws` is used in the method signature to declare that a method can throw exceptions, making it the responsibility of the calling code to handle the exception.
25. How can you create a thread in Java?
You can create a thread in Java in two ways:
1. By implementing the `Runnable` interface and passing it to a `Thread` object.
2. By extending the `Thread` class and overriding the `run()` method.
26. What is the `Collections` framework in Java?
The `Collections` framework is a group of interfaces, classes, and algorithms that provide a set of data structures and utilities for managing and manipulating collections, such as lists, sets, and maps. Examples include `ArrayList`, `HashSet`, `TreeMap`, etc.
27. What is the difference between `HashMap` and `TreeMap` in Java?
`HashMap` is an implementation of the `Map` interface that stores key-value pairs without any order, while `TreeMap` stores key-value pairs in a sorted order based on the natural ordering of keys or a custom comparator.
28. What is the `Iterable` interface in Java?
The `Iterable` interface represents a collection of elements that can be iterated over. It contains a single method, `iterator()`, which returns an `Iterator` to iterate through the elements.
29. What are the different types of memory areas allocated by JVM?
The JVM allocates memory in several areas:
1. **Heap**: Used for storing objects and arrays.
2. **Stack**: Stores method frames, local variables, and partial results.
3. **Method Area**: Stores class structures like method data and metadata.
4. **Program Counter Register**: Stores the address of the current method being executed.
5. **Native Method Stack**: Used for native methods.
30. What is the purpose of the `transient` keyword in Java?
The `transient` keyword is used to indicate that a field should not be serialized. When an object is serialized, transient fields are excluded from the serialization process.
31. What is serialization in Java?
Serialization is the process of converting an object into a byte stream so that it can be saved to a file or transmitted over a network. This process allows an object to be reconstructed later (deserialization).
32. How can you prevent a class from being subclassed in Java?
To prevent a class from being subclassed, you can declare the class as `final`. A `final` class cannot have any subclasses.
33. What is the `instanceof` operator in Java?
The `instanceof` operator checks if an object is an instance of a particular class or implements an interface. It returns `true` if the object is an instance, otherwise `false`.
34. What is the difference between `synchronized` and `lock` in Java?
Both `synchronized` and `lock` are used for synchronization, but:
- `synchronized` is a keyword that can be applied to methods or blocks of code to ensure thread safety.
- `Lock` is an interface in the `java.util.concurrent.locks` package that provides more advanced locking mechanisms with greater control over lock acquisition and release.
35. What is an Enum in Java?
An `Enum` in Java is a special class that represents a group of constants. Enums provide a type-safe way of defining and using constants.
36. What is a `Constructor` in Java?
A constructor is a special method in Java that is used to initialize objects. It is called when an object of a class is created. A constructor has the same name as the class and no return type.
37. What is the difference between `String` and `StringBuilder`?
`String` is immutable, meaning its value cannot be changed once created. `StringBuilder` is mutable, allowing modifications to the string without creating new objects. `StringBuilder` is more efficient for concatenating strings.
38. What is a `Lambda Expression` in Java?
A `Lambda Expression` in Java is a shorthand way of writing a function that can be passed around as an argument to methods. It enables you to write cleaner, more readable code when working with functional interfaces.
39. What is the difference between `==` and `.equals()` in Java?
`==` checks whether two references point to the same memory location, while `.equals()` checks whether the values of two objects are equal.
40. What is the use of the `this` keyword in Java?
The `this` keyword refers to the current instance of a class. It is used to access instance variables and methods, differentiate between local and instance variables, and call other constructors in the same class.
41. What is the difference between `Runnable` and `Callable` in Java?
Both `Runnable` and `Callable` are used to define tasks for execution in a separate thread. However, `Runnable` does not return any result and cannot throw checked exceptions, while `Callable` can return a result and can throw exceptions.
42. What is the `Java Reflection` API?
The Java Reflection API allows you to inspect and manipulate classes, methods, fields, and other metadata at runtime. It provides the ability to dynamically create objects, invoke methods, and get/set field values.
43. What is the difference between `Abstract Class` and `Interface` in Java?
An `abstract class` can have both abstract and concrete methods, and it can have instance fields. An `interface` can only have abstract methods (except for default and static methods in Java 8+) and constants, and it cannot contain instance fields.
44. What is the purpose of the `clone()` method in Java?
The `clone()` method creates and returns a copy of the object. To use it, a class must implement the `Cloneable` interface, and the method creates a shallow copy by default.
45. What is a `HashSet` in Java?
A `HashSet` is a collection that does not allow duplicate elements and does not maintain any order of elements. It is implemented using a hash table and provides constant-time performance for basic operations like add, remove, and contains.
46. What is the purpose of the `default` keyword in Java 8 interfaces?
The `default` keyword is used to define default methods in interfaces. Default methods allow you to add new methods to an interface without breaking existing implementations.
47. What is the difference between `ArrayList` and `CopyOnWriteArrayList` in Java?
`ArrayList` is not thread-safe, while `CopyOnWriteArrayList` is thread-safe. `CopyOnWriteArrayList` creates a copy of the underlying array for each modification, making it more efficient for read-heavy operations, but less efficient for write-heavy operations.
48. What are the main principles of Object-Oriented Programming in Java?
The main principles of OOP in Java are:
1. **Encapsulation**: Bundling data and methods together in a class.
2. **Abstraction**: Hiding implementation details and exposing only relevant information.
3. **Inheritance**: A class can inherit properties and behaviors from another class.
4. **Polymorphism**: The ability of an object to take many forms, typically achieved by method overloading or overriding.
49. What is a `WeakHashMap` in Java?
A `WeakHashMap` is a type of map where the keys are weakly referenced. If there are no strong references to the key, it may be garbage collected, which allows for automatic cleanup of unused entries.
50. What is the use of `Optional` in Java?
`Optional` is a container object which may or may not contain a value. It is used to avoid `NullPointerException` by explicitly handling the case of absent values, providing methods like `ifPresent()`, `orElse()`, etc.
51. What is the difference between `synchronized` method and `synchronized` block in Java?
A `synchronized` method synchronizes the entire method, meaning only one thread can execute the method at a time. A `synchronized` block allows finer control by only synchronizing a specific section of code, improving performance in some cases.
52. What is the `volatile` keyword in Java?
The `volatile` keyword ensures that the value of a variable is always read from the main memory, not from a thread's local cache. It is used in multi-threaded environments to ensure that changes to a variable are visible to all threads.
53. What is the `ThreadPoolExecutor` in Java?
`ThreadPoolExecutor` is a class in the `java.util.concurrent` package that manages a pool of worker threads. It is used to execute tasks concurrently by reusing existing threads from the pool, rather than creating new threads each time.
54. How can you handle deadlocks in Java?
Deadlocks can be prevented by ensuring that all threads acquire locks in the same order. You can also use a `tryLock()` method or use higher-level concurrency utilities like `ReentrantLock` with timeouts to avoid deadlocks.
55. What is a `ReentrantLock` in Java?
`ReentrantLock` is a class in the `java.util.concurrent.locks` package that provides a more flexible mechanism for locking. It allows a thread to lock a resource multiple times (reentrancy) and provides additional features like fairness and timeouts.
56. What are the advantages of using `StringBuilder` over `String`?
`StringBuilder` is mutable, meaning it can be modified without creating new objects, making it more efficient when performing multiple string concatenations. `String` is immutable, which creates a new object for each modification, leading to higher memory consumption and slower performance.
57. What is the purpose of the `default` method in Java interfaces?
The `default` method allows interfaces to have methods with implementations. This was introduced in Java 8 to provide backward compatibility while adding new methods to interfaces.
58. What is the difference between `ArrayList` and `Vector` in Java?
`ArrayList` is not synchronized, making it faster in single-threaded environments, while `Vector` is synchronized, which can make it slower but thread-safe. `Vector` also grows dynamically in a different manner by doubling its size, while `ArrayList` increases its size by 50% when needed.
59. What is the purpose of the `static` keyword in Java?
The `static` keyword is used to create class-level variables and methods that are shared among all instances of the class. A `static` method can be called without creating an instance of the class, and a `static` variable is common to all instances.
60. What is a `Nested Class` in Java?
A `Nested Class` is a class defined within another class. There are two types of nested classes: **Static Nested Class**, which does not have a reference to an instance of the outer class, and **Inner Class**, which has access to the instance variables of the outer class.
61. What is a `constructor` chaining in Java?
Constructor chaining is the process of calling one constructor from another within the same class or from the parent class. This is done using `this()` for chaining within the same class and `super()` to call the parent class constructor.
62. What is the difference between `abstract` class and `interface`?
An `abstract` class can have both abstract and concrete methods, and it can hold instance variables, whereas an `interface` can only have abstract methods (with the exception of default and static methods in Java 8+). A class can implement multiple interfaces but can only extend one abstract class.
63. What is the purpose of `java.util.concurrent` package?
The `java.util.concurrent` package provides utility classes for concurrent programming, including thread-safe collections, atomic variables, and high-level concurrency utilities like `ExecutorService`, `CountDownLatch`, `CyclicBarrier`, and `Semaphore`.
64. What are `synchronized` blocks and their advantages?
A `synchronized` block allows you to lock a specific section of code, ensuring that only one thread can execute that section at a time. It reduces the scope of locking, improving performance compared to synchronizing an entire method.
65. What is `null` in Java?
`null` is a special literal in Java that represents the absence of a reference. It is used to indicate that a reference variable does not point to any object or value.
66. What are the differences between `String`, `StringBuffer`, and `StringBuilder` in Java?
`String` is immutable, meaning its value cannot be changed once created. `StringBuffer` is mutable and thread-safe, while `StringBuilder` is also mutable but not thread-safe. `StringBuilder` is preferred for performance in single-threaded environments.
67. How is memory managed in Java?
Memory management in Java is handled through automatic garbage collection. The JVM manages the heap memory, where objects are allocated, and it uses garbage collectors to automatically reclaim memory used by objects that are no longer referenced.
68. What is the `try-with-resources` statement in Java?
The `try-with-resources` statement, introduced in Java 7, automatically closes resources like streams or files when they are no longer needed. It ensures that resources are closed properly, avoiding memory leaks and exceptions during resource cleanup.
69. What is the difference between `Callable` and `Runnable` in Java?
`Runnable` does not return a result and cannot throw checked exceptions, whereas `Callable` can return a result and throw checked exceptions. `Callable` is often used with `ExecutorService` for tasks that need to return a value.
70. What is a `garbage collector` in Java?
The garbage collector in Java is responsible for automatically reclaiming memory by removing objects that are no longer referenced. It helps to prevent memory leaks and ensures that the heap memory is efficiently used.
71. How does Java handle exceptions?
Java handles exceptions through a mechanism called exception handling, using `try`, `catch`, and `finally` blocks. Exceptions are caught and processed in the `catch` block, while the `finally` block is used for cleanup, regardless of whether an exception occurred or not.
72. What is the difference between `==` and `.equals()` when comparing objects?
`==` checks if two references point to the same memory location (reference comparison), while `.equals()` checks if the contents of two objects are equal (content comparison). Overriding `.equals()` is necessary for meaningful content comparison.
73. What is the significance of the `super()` constructor in Java?
The `super()` constructor is used to call the constructor of the immediate parent class. It must be the first statement in the subclass constructor and is used to initialize the parent class before the subclass can be initialized.
74. How does the `Java Reflection` API work?
The Java Reflection API allows you to inspect and manipulate classes, methods, fields, and other metadata at runtime. Through reflection, you can dynamically create objects, call methods, and modify fields without knowing their details at compile time.
75. What is the difference between `ArrayList` and `LinkedList` in terms of performance?
`ArrayList` is better for random access (get operations) as it provides O(1) time complexity. However, inserting or deleting elements in the middle of the list is slower (O(n)) because elements need to be shifted. `LinkedList` has faster insertions and deletions (O(1)) but slower random access (O(n)) due to the need to traverse the list.
76. What is a `stack` in Java?
A `Stack` in Java is a collection that follows the Last In First Out (LIFO) principle. The most recently added element is the first to be removed. It is implemented as a class in `java.util` and provides methods like `push()`, `pop()`, and `peek()`.
77. What are `default` methods in Java 8?
`default` methods are methods defined in interfaces with a default implementation. They allow interfaces to evolve without breaking existing implementations. A class implementing an interface with a default method can override it if needed.
78. What are `Java annotations`?
Java annotations are metadata that provide additional information to the compiler or runtime environment. They do not affect the program logic but can be used for tasks like code analysis, documentation generation, or runtime processing.
79. What is the `Cloneable` interface in Java?
The `Cloneable` interface is a marker interface that indicates a class can be cloned using the `clone()` method. If a class implements `Cloneable`, it must override the `clone()` method to provide a copy of its objects.
80. What is a `Map` in Java?
A `Map` is an object that maps keys to values. It does not allow duplicate keys, and each key is associated with a single value. The `Map` interface has implementations like `HashMap`, `TreeMap`, and `LinkedHashMap`.
81. What is a `WeakReference` in Java?
A `WeakReference` is a reference that allows an object to be garbage collected when there are no strong references to it. It is often used in caching mechanisms where you want to allow an object to be collected when memory is needed.
82. What is the `final` keyword used for in Java?
The `final` keyword is used to restrict modification. It can be applied to variables (making them constants), methods (preventing them from being overridden), and classes (preventing them from being subclassed).
83. What are `Checked` and `Unchecked exceptions` in Java?
Checked exceptions are exceptions that must be either caught or declared in the method signature (e.g., `IOException`). Unchecked exceptions, also called runtime exceptions, do not need to be explicitly handled (e.g., `NullPointerException`).
84. What is the difference between `HashMap` and `TreeMap` in Java?
`HashMap` stores elements in an unordered fashion and allows null keys and values, while `TreeMap` stores elements in a sorted order based on the natural ordering of keys or a specified comparator. `TreeMap` does not allow null keys.
85. What is `ThreadLocal` in Java?
`ThreadLocal` is a class that provides thread-local variables. Each thread accessing a `ThreadLocal` variable gets its own independent copy, ensuring that the variable is not shared between threads.
86. What is the purpose of the `assert` keyword in Java?
The `assert` keyword is used for debugging purposes to test assumptions about the program. If the expression provided in the `assert` statement evaluates to `false`, an `AssertionError` is thrown.
87. How do you create a thread in Java?
A thread can be created by either implementing the `Runnable` interface or by extending the `Thread` class. The `run()` method defines the code that the thread will execute, and the thread is started using the `start()` method.
88. What is the `Factory` design pattern?
The `Factory` pattern provides an interface for creating objects, but allows subclasses to alter the type of objects that will be created. It is used to create objects without specifying the exact class of the object that will be created.
89. What is a `Singleton` pattern in Java?
The `Singleton` pattern ensures that a class has only one instance and provides a global point of access to that instance. It can be implemented by making the constructor private and providing a static method to get the instance.
90. What is the purpose of `Collections` class in Java?
The `Collections` class provides static methods to operate on or return collections. It includes methods for sorting, reversing, shuffling, and performing various other operations on lists, sets, and other collection types.
91. What is the difference between `StringBuffer` and `StringBuilder`?
`StringBuffer` is thread-safe and synchronized, while `StringBuilder` is not thread-safe but offers better performance in single-threaded environments because of the lack of synchronization.
92. What is the use of `super` keyword in Java?
The `super` keyword refers to the immediate parent class of the current object. It can be used to access parent class methods, constructors, and variables. It is also used to invoke the parent class constructor.
93. What is the difference between `==` and `.equals()` in comparing two `String` objects?
The `==` operator checks if two references point to the same object in memory, while `.equals()` checks if the values of the two `String` objects are equal.
94. What is the `Clone()` method in Java?
The `Clone()` method is used to create a copy of an object. It is defined in the `Object` class and must be overridden if the object supports cloning. The object must implement the `Cloneable` interface to be cloned.
95. What are the benefits of using `lambda expressions` in Java?
`Lambda expressions` allow you to write more concise and readable code, especially when working with functional interfaces. They also enable the use of functional programming techniques, such as passing behavior as parameters to methods.
96. What is the difference between `String` and `StringBuilder` in terms of mutability?
`String` is immutable, meaning once it is created, its value cannot be changed. `StringBuilder` is mutable, meaning it can be modified after creation, making it more efficient for tasks like string concatenation.
97. What is a `Marker Interface` in Java?
A `Marker Interface` is an interface that does not contain any methods. It is used to indicate that a class has some specific property or behavior. Common examples include `Serializable` and `Cloneable`.
98. What is the difference between `Set` and `List` in Java?
A `Set` does not allow duplicate elements, while a `List` allows duplicates. A `Set` is unordered, while a `List` maintains the order of elements.
99. What is the `hashCode()` method in Java?
The `hashCode()` method is used to compute a hash code for an object, which is used by hash-based collections like `HashMap`. It is important for the `hashCode()` method to be consistent with the `equals()` method to ensure correct functioning of these collections.
100. What is the difference between `equals()` and `compareTo()` in Java?
`equals()` checks if two objects are equal based on their content, while `compareTo()` is used to compare two objects for ordering. `compareTo()` returns an integer value: a negative value if the first object is less than the second, zero if they are equal, and a positive value if the first object is greater than the second.