0% found this document useful (0 votes)
3 views

java Interview Questions

Uploaded by

khajulrehaman77
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

java Interview Questions

Uploaded by

khajulrehaman77
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 7

1. **What is Java?

**
Java is a high-level, object-oriented programming language that is platform-
independent. It follows the principle of "write once, run anywhere," meaning
compiled Java code can run on all platforms that support Java without needing
recompilation.

2. **What are the key features of Java?**


Key features of Java include:
- **Object-Oriented**: Everything in Java is treated as an object.
- **Platform-Independent**: Java code can run on any machine with a JVM.
- **Simple**: Java has a simple syntax, easy to learn.
- **Secure**: Provides built-in security features like bytecode verification.
- **Portable**: Java code is architecture-neutral, and Java programs are easily
portable across different platforms.
- **Robust**: Strong memory management, exception handling, and garbage
collection.
- **Multithreaded**: Supports multiple threads of execution.
- **High Performance**: Just-In-Time (JIT) compiler optimizes code during
execution.

3. **What is JVM, JRE, and JDK?**


- **JVM (Java Virtual Machine)**: Executes Java bytecode and provides platform
independence.
- **JRE (Java Runtime Environment)**: Includes JVM and libraries necessary to
run Java applications.
- **JDK (Java Development Kit)**: Includes JRE along with development tools like
the compiler (`javac`) for writing and testing Java programs.

4. **What is a class in Java?**


A class is a blueprint for objects. It defines a type by bundling data (fields)
and methods (behaviors) to operate on that data. Objects are created from classes.

5. **What is an object in Java?**


An object is an instance of a class. It has a state (attributes or fields) and
behavior (methods). Objects are created using the `new` keyword.

6. **What is the difference between a class and an object?**


A class is a blueprint or template for creating objects, while an object is an
instance of a class.

7. **What is inheritance in Java?**


Inheritance allows one class (subclass) to inherit the fields and methods of
another class (superclass). This promotes code reuse.

8. **What is method overloading?**


Method overloading is a feature in Java where multiple methods can have the same
name but different parameter lists (different types, numbers, or both).

9. **What is method overriding?**


Method overriding occurs when a subclass provides a specific implementation for
a method that is already defined in its superclass.

10. **What is encapsulation in Java?**


Encapsulation is the process of wrapping data (variables) and code (methods)
together as a single unit and restricting access to certain components using access
modifiers like `private`.

11. **What is polymorphism in Java?**


Polymorphism allows objects of different classes to be treated as objects of a
common superclass. It enables one method to perform different tasks based on the
object that it is acting upon. It can be achieved through method overriding
(runtime polymorphism) and method overloading (compile-time polymorphism).

12. **What is abstraction in Java?**


Abstraction is the concept of hiding the implementation details and showing
only the functionality to the user. It can be achieved using abstract classes or
interfaces.

13. **What is the difference between an abstract class and an interface?**


- **Abstract class**: Can have both abstract and non-abstract methods, and
allows fields.
- **Interface**: Only abstract methods (until Java 8, which introduced default
and static methods). All fields are implicitly `public`, `static`, and `final`.

14. **What are constructors in Java?**


Constructors are special methods used to initialize objects. They have the same
name as the class and no return type.

15. **What is a default constructor?**


A default constructor is a constructor that takes no arguments and is
automatically provided by the compiler if no other constructors are defined.

16. **What is a parameterized constructor?**


A parameterized constructor is one that accepts arguments to initialize an
object with specific values.

17. **What is the 'this' keyword in Java?**


The `this` keyword refers to the current object in a method or constructor. It
is used to resolve naming conflicts between class fields and parameters or methods.

18. **What is the 'super' keyword in Java?**


The `super` keyword is used to refer to the parent class (superclass) object.
It can be used to access parent class methods, fields, and constructors.

19. **What is the difference between method overloading and method overriding?**
- **Method Overloading**: Same method name with different parameter lists in
the same class (compile-time polymorphism).
- **Method Overriding**: Subclass provides a specific implementation of a
method already defined in the superclass (runtime polymorphism).

20. **What are access modifiers in Java?**


Access modifiers define the scope of variables, methods, and classes. Java has
four main access modifiers:
- **public**: Accessible from any class.
- **private**: Accessible only within the declared class.
- **protected**: Accessible within the same package and subclasses.
- **default (no modifier)**: Accessible only within the same package.

21. **What is static in Java?**


`static` is a keyword in Java used for memory management. It can be applied to
variables, methods, blocks, and nested classes. A static member belongs to the
class rather than instances of the class.

22. **What is the difference between a static and non-static method in Java?**
- **Static Method**: Belongs to the class, not the instance. It can be called
without creating an instance of the class.
- **Non-static Method**: Belongs to an object of the class. It can access
instance variables and methods.
23. **What is the final keyword in Java?**
The `final` keyword in Java is used to restrict the user. It can be applied to
variables (to make them constants), methods (to prevent overriding), and classes
(to prevent inheritance).

24. **What is the difference between String, StringBuilder, and StringBuffer?**


- **String**: Immutable, meaning once created, its value cannot be changed.
- **StringBuilder**: Mutable, but not thread-safe. Used when thread
synchronization is not required.
- **StringBuffer**: Mutable and thread-safe, meaning it can be safely used in a
multi-threaded environment.

25. **What is the difference between == operator and equals() method?**


- `==` compares object references (whether two references point to the same
memory location).
- `equals()` compares the actual content of the objects.

26. **What is the hashCode() method in Java?**


`hashCode()` provides a unique integer value associated with each object, which
is used in hashing-based collections like `HashMap`, `HashSet`, etc.

27. **What is a package in Java?**


A package is a namespace that organizes a set of related classes and
interfaces. Java provides built-in packages like `java.lang`, `java.util`, and
allows users to create their own.

28. **What is the use of import statement in Java?**


The `import` statement allows access to classes from other packages. It enables
the reuse of code written in other packages.

29. **What is the difference between an Array and an ArrayList in Java?**


- **Array**: Fixed-size data structure that stores elements of the same type.
- **ArrayList**: Resizable array that can grow or shrink dynamically. It is
part of the Java `Collections` framework.

30. **What is the Collections framework in Java?**


The Java Collections framework is a unified architecture for representing and
manipulating collections. It includes interfaces, implementations, and algorithms
to work with data.

31. **What is the difference between HashMap and Hashtable?**


- **HashMap**: Not synchronized and allows one `null` key and multiple `null`
values.
- **Hashtable**: Synchronized and does not allow `null` keys or values.

32. **What is the difference between HashSet and TreeSet?**


- **HashSet**: Unordered, allows `null`, faster access due to hashing.
- **TreeSet**: Ordered, does not allow `null`, slower but maintains elements in
sorted order.

33. **What is an Iterator in Java?**


An `Iterator` is an interface in Java used to iterate over collections like
`List`, `Set`, etc. It allows traversal of the collection and removal of elements
from the collection.

34. **What is the difference between Iterator and ListIterator?**


- **Iterator**: Can traverse in a forward direction only.
- **ListIterator**: Can traverse in both forward and backward directions and
modify the list during iteration.

35. **What is an Exception in Java?**


An exception is an event that disrupts the normal flow of the program. Java
provides a mechanism to handle runtime errors through the use of exceptions.

36. **What is the difference between Checked and Unchecked Exceptions?**


- **Checked Exceptions**: Checked at compile-time (e.g., `IOException`,
`SQLException`).
- **Unchecked Exceptions**: Occur at runtime (e.g., `NullPointerException`,
`ArithmeticException`).

37. **What is the use of try-catch

in Java?**
The `try-catch` block is used to handle exceptions. Code that may throw an
exception is placed inside the `try` block, and exception handling code is placed
in the `catch` block.

38. **What is a finally block in Java?**


A `finally` block is used to execute important code such as cleanup code. It
always executes, regardless of whether an exception occurred or not.

39. **What is a throw and throws keyword in Java?**


- `throw`: Used to explicitly throw an exception.
- `throws`: Used to declare an exception in the method signature, indicating
that the method may throw an exception.

40. **What is the difference between throw and throws in Java?**


- `throw`: Used inside a method to explicitly throw an exception.
- `throws`: Used in method declaration to indicate that the method can throw an
exception.

41. **What is multi-threading in Java?**


Multi-threading is a process of executing multiple threads simultaneously. Java
provides built-in support for multi-threading by using the `Thread` class and
`Runnable` interface.

42. **How can we create a thread in Java?**


Threads can be created in two ways:
- By implementing the `Runnable` interface and passing the object to the
`Thread` constructor.
- By extending the `Thread` class and overriding the `run()` method.

43. **What is the life cycle of a thread in Java?**


The thread life cycle consists of the following stages:
- **New**: The thread is created but not yet started.
- **Runnable**: The thread is ready to run but waiting for CPU time.
- **Blocked**: The thread is waiting for a resource.
- **Running**: The thread is actively executing.
- **Terminated**: The thread has finished executing.

44. **What is synchronization in Java?**


Synchronization is a mechanism that ensures that two or more threads do not
simultaneously execute a block of code (critical section) that manipulates shared
data. It prevents data inconsistency in multi-threaded environments.

45. **What is the difference between process and thread in Java?**


- **Process**: An independent program in execution.
- **Thread**: A small unit of a process that can execute concurrently.

46. **What is deadlock in Java?**


A deadlock is a situation where two or more threads are blocked forever, each
waiting for the other to release a resource.

47. **What is the difference between wait() and sleep() in Java?**


- `wait()`: Causes the current thread to wait until another thread calls
`notify()` or `notifyAll()` on the same object. Releases the lock on the object.
- `sleep()`: Causes the thread to pause for a specified amount of time without
releasing the lock.

48. **What is a daemon thread in Java?**


A daemon thread is a background thread that runs in the background and performs
tasks like garbage collection. It terminates when all non-daemon threads terminate.

49. **What is the purpose of garbage collection in Java?**


Garbage collection automatically reclaims memory by identifying and discarding
objects that are no longer in use, preventing memory leaks.

50. **What is the finalize() method in Java?**


The `finalize()` method is invoked by the garbage collector before reclaiming
the memory occupied by an object. It is used to perform cleanup actions before an
object is destroyed.

51. **What is the difference between throw and finally in Java?**


- `throw`: Used to explicitly throw an exception.
- `finally`: A block of code that is executed after the `try` and `catch`
blocks, regardless of whether an exception occurred.

52. **What is JDBC in Java?**


JDBC (Java Database Connectivity) is an API that allows Java applications to
interact with databases. It provides methods to query and update data in a
database.

53. **What are the steps to connect to a database in Java using JDBC?**
Steps to connect to a database using JDBC:
- Load the JDBC driver.
- Establish a connection using `DriverManager.getConnection()`.
- Create a `Statement` or `PreparedStatement` object to execute queries.
- Execute the query and process the results.
- Close the connection.

54. **What is the difference between Statement and PreparedStatement in JDBC?**


- **Statement**: Used for executing simple SQL queries.
- **PreparedStatement**: Used for executing parameterized SQL queries and
offers better performance.

55. **What is a Servlet in Java?**


A servlet is a Java class used to handle HTTP requests and generate responses.
It is a server-side component that runs in a web server or application server.

56. **What is the difference between doGet() and doPost() methods in Servlets?**
- **doGet()**: Handles HTTP GET requests. Used for requests where the data is
appended to the URL.
- **doPost()**: Handles HTTP POST requests. Used for requests where data is
sent in the request body.

57. **What is JSP (JavaServer Pages)?**


JSP is a technology that allows developers to create dynamic web pages using
HTML, XML, and Java code. JSP files are compiled into servlets and run on a server.

58. **What is the difference between Servlet and JSP?**


- **Servlet**: Java code embedded in HTML. It is harder to write, but better
for controlling logic.
- **JSP**: HTML with embedded Java code. It is easier to write and better for
UI design.

59. **What is session management in Java?**


Session management is the technique of maintaining a user's state across
multiple HTTP requests. Common session management techniques include cookies, URL
rewriting, and `HttpSession`.

60. **What is the Singleton Design Pattern in Java?**


The Singleton pattern ensures that a class has only one instance and provides a
global point of access to it. It is used to prevent multiple objects being created
for a class.

61. **What is the Factory Design Pattern in Java?**


The Factory pattern provides a way to create objects without exposing the
instantiation logic to the client and refers to the newly created object using a
common interface.

62. **What is the Observer Design Pattern in Java?**


The Observer pattern defines a one-to-many dependency between objects so that
when one object changes state, all its dependents are notified and updated
automatically.

63. **What is the difference between ArrayList and LinkedList in Java?**


- **ArrayList**: Implements a resizable array. Access is faster due to
indexing, but insertion/deletion is slower.
- **LinkedList**: Implements a doubly-linked list. Insertion and deletion are
faster, but access is slower as it requires traversal.

64. **What is the Map interface in Java?**


The `Map` interface represents a collection of key-value pairs. It does not
allow duplicate keys and each key can map to only one value. Examples include
`HashMap`, `TreeMap`, and `LinkedHashMap`.

65. **What is the difference between HashMap and TreeMap?**


- **HashMap**: Unordered collection based on hashing. Allows `null` key and
multiple `null` values.
- **TreeMap**: Sorted collection based on the natural ordering of keys. Does
not allow `null` keys.

66. **What is fail-fast in Java?**


Fail-fast is a property of iterators. If a collection is modified while it is
being iterated, a `ConcurrentModificationException` is thrown.

67. **What is a Comparator in Java?**


A `Comparator` is an interface used to define custom sorting logic for
collections. It allows sorting based on multiple criteria.

68. **What is the difference between Comparable and Comparator?**


- **Comparable**: Used to define natural ordering. The class itself implements
`Comparable`.
- **Comparator**: Used to define custom ordering. A separate class implements
`Comparator`.
69. **What is the purpose of the transient keyword in Java?**
The `transient` keyword is used to indicate that a field should not be
serialized. During serialization, transient fields are ignored.

70. **What is serialization in Java?**


Serialization is the process of converting an object's state into a byte stream
so that it can be saved to a file or transmitted over a network.

71. **What is deserialization in Java?**


Deserialization is the reverse process of serialization, where a byte stream is
converted back into an object.

72. **What is an annotation in Java?**


An annotation is a form of metadata that provides data about a program but is
not part of the program itself. Annotations are used to provide information to the
compiler or runtime.

73. **What is the use of the @Override annotation in Java?**


The `@Override` annotation is used to indicate that a method is intended to
override a method in a superclass. It helps prevent errors by alerting the compiler
if the method signature does not match.

74. **What is the difference between @Override and @Deprecated annotations in Java?
**
- `@Override`: Indicates a method is overriding a method in the superclass.
- `@Deprecated`: Marks a method, class, or field as obsolete and indicates that
it should not be used.

75. **What is the difference between the final, finally, and finalize keywords in
Java?**
- `final`: Used to declare constants, prevent method overriding, or prevent
inheritance.
- `finally`: Block used for code that will always

be executed, typically for cleanup code.


- `finalize`: Method used by the garbage collector before destroying an object.

You might also like