Core java interview questions and answers [ top 100 FAQ ]
Here are the Top 100 Core Java Interview Questions and Answers that cover a wide range of topics to help you prepare for interviews. These questions are categorized into different sections like basic concepts, OOP concepts, exception handling, collections, multi-threading, etc.
1. What are the main features of Java?
Answer:
- Object-Oriented: Java follows OOP principles (Encapsulation, Inheritance, Polymorphism, Abstraction).
- Platform-Independent: Write once, run anywhere (WORA) due to JVM (Java Virtual Machine).
- Simple: Java eliminates complexity by removing pointers, operator overloading, etc.
- Secure: Provides features like bytecode verification, access control, etc.
- Multithreaded: Supports multithreading for efficient CPU utilization.
2. What is the difference between JDK, JRE, and JVM?
Answer:
- JDK (Java Development Kit): A software development kit that includes JRE along with development tools (compiler, debugger, etc.).
- JRE (Java Runtime Environment): A runtime environment that includes JVM and libraries to run Java applications.
- JVM (Java Virtual Machine): An abstract computing machine that enables Java bytecode execution on any platform.
3. What is the purpose of the main()
method in Java?
Answer:
The main()
method is the entry point for any Java application. The Java Virtual Machine (JVM) calls the main()
method to start execution of the program.
4. What is the difference between ==
and equals()
method in Java?
Answer:
==
compares the memory addresses (references) of two objects.equals()
compares the actual contents of two objects (if overridden).
5. What are the data types in Java?
Answer:
Java supports two categories of data types:
- Primitive types: byte, short, int, long, float, double, char, boolean.
- Reference types: Arrays, Classes, Interfaces.
6. What is autoboxing and unboxing in Java?
Answer:
- Autoboxing: Automatic conversion of primitive types to wrapper classes (e.g.,
int
toInteger
). - Unboxing: Automatic conversion of wrapper classes to primitive types (e.g.,
Integer
toint
).
7. What is the difference between ArrayList
and LinkedList
?
Answer:
- ArrayList: Implements a dynamic array. Provides fast access (constant time) for elements but slower for insertions and deletions (linear time).
- LinkedList: Implements a doubly linked list. Slower for access but faster for insertions and deletions compared to ArrayList.
8. What is the final
keyword in Java?
Answer:
final
variable: The value cannot be changed once assigned.final
method: Cannot be overridden by subclasses.final
class: Cannot be subclassed.
9. What is an abstract class in Java?
Answer:
An abstract class is a class that cannot be instantiated and may contain abstract methods (methods without implementation). Subclasses must implement the abstract methods.
10. What is the difference between an abstract class and an interface?
Answer:
- Abstract class: Can have both abstract and non-abstract methods, can have constructors, can have instance variables.
- Interface: Can only have abstract methods (prior to Java 8), cannot have instance variables, no constructors, and supports multiple inheritance.
11. What is the super
keyword in Java?
Answer:
The super
keyword refers to the immediate parent class of the current object. It is used to access parent class methods and constructors.
12. What is the purpose of the this
keyword?
Answer:
The this
keyword refers to the current instance of the class. It is used to access instance variables and methods of the current object.
13. What is the difference between String
, StringBuilder
, and StringBuffer
?
Answer:
- String: Immutable, cannot be changed after creation.
- StringBuilder: Mutable, not synchronized (faster).
- StringBuffer: Mutable, synchronized (slower than StringBuilder but thread-safe).
14. What is method overloading in Java?
Answer:
Method overloading occurs when a class has multiple methods with the same name but different parameters (either in type or number).
15. What is method overriding in Java?
Answer:
Method overriding occurs when a subclass provides its specific implementation of a method that is already defined in its superclass.
16. What is the difference between method overloading and method overriding?
Answer:
- Method overloading: Same method name but different parameters.
- Method overriding: Same method signature in the superclass and subclass.
17. What is a constructor in Java?
Answer:
A constructor is a special type of method used to initialize objects. It has the same name as the class and no return type.
18. What is the difference between a constructor and a method?
Answer:
- Constructor: Initializes objects, cannot be called explicitly, has no return type.
- Method: Defines behavior and can be called explicitly, has a return type.
19. What is the purpose of the transient
keyword in Java?
Answer:
The transient
keyword is used to indicate that a field should not be serialized when the object is serialized.
20. What is an enum in Java?
Answer:
An enum is a special class that represents a group of constants (unchangeable variables, like final
variables).
21. What is a HashMap
in Java?
Answer:
A HashMap
is a collection that stores key-value pairs. It does not maintain any order and allows one null
key and multiple null
values.
22. What is the difference between HashMap
and Hashtable
?
Answer:
- HashMap: Not synchronized, allows one null key and multiple null values.
- Hashtable: Synchronized, does not allow any null keys or values.
23. What is a LinkedHashMap
in Java?
Answer:
A LinkedHashMap
is a HashMap
that maintains the insertion order of the keys.
24. What is the Iterator
interface in Java?
Answer:
The Iterator
interface is used to iterate over a collection (like List, Set) and provides methods like next()
, hasNext()
, and remove()
.
25. What is the ListIterator
interface in Java?
Answer:
The ListIterator
is a special type of iterator that allows iteration over a List
in both forward and backward directions.
26. What is the difference between ArrayList
and Vector
?
Answer:
- ArrayList: Not synchronized, offers better performance.
- Vector: Synchronized, slower performance.
27. What is the difference between ArrayList
and LinkedList
?
Answer:
- ArrayList: Uses dynamic arrays, provides faster access and slower insertion/deletion.
- LinkedList: Uses doubly linked list, slower access but faster insertion and deletion.
28. What is the Map
interface in Java?
Answer:
The Map
interface represents an object that maps keys to values. It does not allow duplicate keys.
29. What is the HashSet
in Java?
Answer:HashSet
is a collection that implements the Set
interface and does not allow duplicate elements.
30. What is the TreeSet
in Java?
Answer:TreeSet
is a Set
that implements a sorted collection and stores elements in ascending order.
31. What is Comparable
interface in Java?
Answer:
The Comparable
interface defines the compareTo()
method that is used to compare the current object with another object of the same class.
32. What is Comparator
interface in Java?
Answer:
The Comparator
interface defines the compare()
method and is used for comparing objects of different classes or when sorting in different orders.
33. What is the difference between StringBuilder
and StringBuffer
?
Answer:
- StringBuilder: Not synchronized (faster for single-threaded operations).
- StringBuffer: Synchronized (thread-safe but slower).
34. What is the finally
block in Java?
Answer:
The finally
block is always executed, regardless of whether an exception is thrown or not. It is typically used to close resources like files or database connections.
35. What is exception handling in Java?
Answer:
Exception handling in Java is the process of catching and dealing with runtime errors using try
, catch
, throw
, throws
, and finally
.
36. What is the difference between throw
and throws
in Java?
Answer:
throw
: Used to explicitly throw an exception.throws
: Declares the exceptions that a method might throw.
37. What is the StackOverflowError
in Java?
Answer:
A StackOverflowError
occurs when the stack (memory used for method calls) exceeds its limit, typically due to infinite recursion.
38. What is a NullPointerException
in Java?
Answer:
A NullPointerException
occurs when a program attempts to use a reference that points to null
.
39. What is synchronization
in Java?
Answer:
Synchronization is a technique that ensures that only one thread can access a resource at a time, preventing data corruption in multithreaded environments.
40. What is the difference between sleep()
and wait()
in Java?
Answer:
sleep()
: Puts the current thread to sleep for a specified time without releasing the lock.wait()
: Causes the current thread to release the lock and wait until another thread notifies it.
41. What is deadlock
in Java?
Answer:
Deadlock is a situation where two or more threads are blocked forever because they are waiting for each other to release resources.
42. What is the volatile
keyword in Java?
Answer:
The volatile
keyword indicates that a variable may be changed by multiple threads, ensuring that the most recent value is always visible to all threads.
43. What is Thread
class in Java?
Answer:
The Thread
class represents a thread of execution. It can be extended to create custom threads.
44. What is Runnable
interface in Java?
Answer:
The Runnable
interface represents a task to be executed by a thread. It has a single method run()
.
45. What is ExecutorService
in Java?
Answer:ExecutorService
is an interface that provides methods to manage and control thread execution, like submit()
, invokeAll()
, etc.
46. What is a Callable
interface in Java?
Answer:
The Callable
interface is similar to Runnable
, but it can return a result and throw an exception.
47. What is ThreadPoolExecutor
in Java?
Answer:ThreadPoolExecutor
is an implementation of ExecutorService
that manages a pool of worker threads to efficiently execute tasks.
48. What is a ForkJoinPool
in Java?
Answer:ForkJoinPool
is a specialized thread pool for parallelizing tasks in a way that allows work to be divided into smaller tasks and combined efficiently.
49. What is the ExecutorService
shutdown method?
Answer:
The shutdown()
method is used to stop the execution of an ExecutorService
. It prevents new tasks from being submitted but allows already submitted tasks to complete.
50. What are the states of a thread in Java?
Answer:
A thread can be in one of the following states:
- New: Thread is created but not started yet.
- Runnable: Thread is ready to run and waiting for CPU time.
- Blocked: Thread is waiting for a lock.
- Waiting: Thread is waiting for another thread to perform a particular action.
- Timed Waiting: Thread is waiting for a specified period.
- Terminated: Thread has completed execution.
51. What is the join()
method in Java?
Answer:
The join()
method allows one thread to wait for another thread to finish before it proceeds.
52. What is the ThreadLocal
class in Java?
Answer:
The ThreadLocal
class provides thread-local variables. Each thread has its own copy of the variable.
53. What is the purpose of synchronized
keyword in Java?
Answer:
The synchronized
keyword ensures that only one thread can access a method or block of code at a time, providing thread safety.
54. What are the differences between wait()
, notify()
, and notifyAll()
in Java?
Answer:
wait()
: Causes the current thread to wait until notified.notify()
: Wakes up a single thread waiting on the object's monitor.notifyAll()
: Wakes up all threads waiting on the object's monitor.
55. What is the difference between ArrayList
and Vector
?
Answer:
- ArrayList: Not synchronized, faster for single-threaded access.
- Vector: Synchronized, slower but thread-safe.
56. What is the use of hashCode()
method in Java?
Answer:
The hashCode()
method returns a unique integer for an object, which helps in organizing data structures like HashMap
or HashSet
.
57. What is serialization
in Java?
Answer:
Serialization is the process of converting an object into a byte stream for storage or transmission.
58. What is the transient
keyword in Java?
Answer:
The transient
keyword is used to indicate that a field should not be serialized.
59. What is the purpose of the clone()
method in Java?
Answer:
The clone()
method is used to create and return a copy of an object.
60. What are the different types of memory in JVM?
Answer:
- Heap: Stores objects and arrays.
- Stack: Stores method calls and local variables.
- Method Area: Stores class structures (fields, methods).
- PC Register: Stores address of the currently executing instruction.
61. What is garbage collection in Java?
Answer:
Garbage collection is the process of automatically reclaiming memory by destroying objects that are no longer reachable.
62. What are the different garbage collectors in Java?
Answer:
Java has multiple garbage collectors:
- Serial GC
- Parallel GC
- CMS (Concurrent Mark-Sweep) GC
- G1 (Garbage-First) GC
63. What is the difference between ==
and equals()
in comparing objects?
Answer:
==
compares references or memory addresses.equals()
compares the actual contents of the objects (if overridden).
64. What is a weak reference
in Java?
Answer:
A weak reference is a reference that does not prevent an object from being garbage collected.
65. What is the System.gc()
method in Java?
Answer:System.gc()
suggests to the JVM to perform garbage collection, but it is not guaranteed.
66. What is finalize()
method in Java?
Answer:
The finalize()
method is called by the garbage collector before an object is garbage collected. It is used to perform cleanup operations. (Not commonly used in modern Java).
67. What is the assert
keyword in Java?
Answer:
The assert
keyword is used to assert an assumption or condition that must hold true during execution. If the condition is false, an AssertionError
is thrown.
68. What are synchronized
blocks in Java?
Answer:
Synchronized blocks in Java are used to lock a particular section of code, ensuring that only one thread can access it at a time.
69. What are lambda expressions
in Java?
Answer:
Lambda expressions are a way to pass behavior as arguments to methods, providing a clear and concise way to represent one method interface using an expression.
70. What is the Stream
API in Java?
Answer:
The Stream API allows functional-style operations on sequences of elements (like filtering, mapping, sorting) to process collections of objects.
71. What is the default
keyword in Java interfaces?
Answer:
The default
keyword allows methods in interfaces to have a default implementation.
72. What is the Optional
class in Java?
Answer:Optional
is a container object used to represent a value that may or may not be present, reducing the need for explicit null checks.
73. What is the Comparator
interface in Java?
Answer:Comparator
is used to define a custom comparison logic for sorting or ordering objects.
74. What is the difference between Collections.sort()
and Arrays.sort()
?
Answer:
Collections.sort()
: Sorts a list.Arrays.sort()
: Sorts an array.
75. How does the hashCode()
method work in Java?
Answer:
The hashCode()
method provides a unique identifier for objects used in hashing-based collections like HashMap
.
76. What is the difference between LinkedList
and ArrayList
?
Answer:
- ArrayList: Uses an array to store elements, fast access time, slow insertion.
- LinkedList: Uses a doubly linked list, slower access time, faster insertion.
77. What is a singleton
class in Java?
Answer:
A singleton class ensures that only one instance of the class exists in the JVM and provides a global point of access to it.
78. What is the notify()
method used for?
Answer:
The notify()
method is used to wake up one thread waiting on an object's monitor.
79. What are functional interfaces in Java?
Answer:
A functional interface is an interface that has exactly one abstract method, used as the basis for lambda expressions and method references.
80. What is a volatile
keyword in Java?
Answer:
The volatile
keyword ensures that updates to a variable are visible to all threads.
Comments
Post a Comment