Java Freshers Interview Questions and Answers for freshers

100 Java Interview Questions and Answers for Freshers
  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 is a general-purpose programming language intended to let application developers "write once, run anywhere" (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.
  2. What are the features of Java?

    • Answer: Key features include platform independence, object-oriented programming, robustness, security, architecture-neutral, portability, interpreted and compiled, high performance, multithreading, dynamic, and distributed.
  3. What is the difference between JDK, JRE, and JVM?

    • Answer: JDK (Java Development Kit) is a complete package including JRE, compilers, debuggers, and other development tools. JRE (Java Runtime Environment) includes the JVM and Java libraries needed to run Java applications. JVM (Java Virtual Machine) is an abstract machine that executes Java bytecode.
  4. What is an object?

    • Answer: An object is an instance of a class. It represents a specific entity with its own state (data) and behavior (methods).
  5. What is a class?

    • Answer: A class is a blueprint or template for creating objects. It defines the data (attributes) and behavior (methods) that objects of that class will have.
  6. Explain the concept of inheritance in Java.

    • Answer: Inheritance allows a class (subclass or derived class) to inherit the properties and methods of another class (superclass or base class). It promotes code reusability and establishes an "is-a" relationship between classes.
  7. What are the types of inheritance in Java?

    • Answer: Java supports single inheritance (a class inheriting from only one superclass) and multiple inheritance through interfaces (a class implementing multiple interfaces).
  8. What is polymorphism?

    • Answer: Polymorphism means "many forms." It allows objects of different classes to be treated as objects of a common type. This is achieved through method overriding and method overloading.
  9. What is method overriding?

    • Answer: Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. The method signature (name and parameters) must be identical.
  10. What is method overloading?

    • Answer: Method overloading is the ability to define multiple methods within the same class that have the same name but different parameters (either number of parameters or types of parameters).
  11. What is encapsulation?

    • Answer: Encapsulation is the bundling of data (attributes) and methods (behavior) that operate on that data within a class. It protects data integrity by restricting direct access to the attributes and providing controlled access through methods (getters and setters).
  12. What is abstraction?

    • Answer: Abstraction is the process of hiding complex implementation details and showing only essential information to the user. In Java, it is achieved through abstract classes and interfaces.
  13. What is an abstract class?

    • Answer: An abstract class is a class that cannot be instantiated. It serves as a blueprint for subclasses and can contain both abstract methods (methods without implementation) and concrete methods (methods with implementation).
  14. What is an interface?

    • Answer: An interface is a completely abstract class. It contains only constants and abstract methods. A class can implement multiple interfaces, enabling multiple inheritance.
  15. 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 it can implement multiple interfaces.
  16. What are access modifiers in Java?

    • Answer: Access modifiers control the visibility and accessibility of class members (variables and methods). They include `public`, `private`, `protected`, and default (package-private).
  17. Explain the difference between `public`, `private`, `protected`, and default access modifiers.

    • Answer: `public`: Accessible from anywhere. `private`: Accessible only within the same class. `protected`: Accessible within the same package and subclasses, even in different packages. Default: Accessible only within the same package.
  18. What is a constructor?

    • Answer: A constructor is a special method used to initialize objects of a class. It has the same name as the class and is automatically called when an object is created.
  19. What is a static method?

    • Answer: A static method belongs to the class itself, not to any specific object of the class. It can be called directly using the class name.
  20. What is a static variable?

    • Answer: A static variable is a class variable that is shared by all objects of the class. Only one copy of the static variable exists, regardless of the number of objects.
  21. What is the difference between `==` and `.equals()`?

    • Answer: `==` compares object references (memory addresses), while `.equals()` compares the content of objects. For custom classes, you need to override the `equals()` method to define how objects should be compared.
  22. What is an exception?

    • Answer: An exception is an event that disrupts the normal flow of program execution. It is an object that represents an error or exceptional condition.
  23. What is exception handling?

    • Answer: Exception handling is the mechanism of gracefully handling exceptions to prevent program crashes. It involves using `try`, `catch`, and `finally` blocks.
  24. Explain the `try`, `catch`, and `finally` blocks.

    • Answer: `try`: Contains the code that might throw an exception. `catch`: Handles specific types of exceptions. `finally`: Contains code that always executes, regardless of whether an exception occurred.
  25. What is a checked exception?

    • Answer: A checked exception is an exception that the compiler forces you to handle (either by using a `try-catch` block or declaring it in the method signature using `throws`).
  26. What is an unchecked exception?

    • Answer: An unchecked exception is an exception that the compiler does not force you to handle. These are typically runtime exceptions (e.g., `NullPointerException`, `ArrayIndexOutOfBoundsException`).
  27. What is the difference between `throw` and `throws` keywords?

    • Answer: `throw` is used to explicitly throw an exception object. `throws` is used in a method signature to declare that the method might throw a specific checked exception.
  28. What is a `finally` block used for?

    • Answer: The `finally` block is used to execute code that must always be executed, regardless of whether an exception is thrown or caught. It's often used for cleanup tasks (e.g., closing files or database connections).
  29. 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. Any operation that appears to modify a `String` actually creates a new `String` object.
  30. What is a StringBuffer in Java?

    • Answer: A `StringBuffer` is a mutable sequence of characters. It allows modifications (insertions, deletions, etc.) to the string without creating new objects. It is synchronized, making it thread-safe but less performant than StringBuilder.
  31. What is a StringBuilder in Java?

    • Answer: A `StringBuilder` is also a mutable sequence of characters, similar to `StringBuffer`, but it is not synchronized. This makes it faster than `StringBuffer` but not thread-safe.
  32. What is the difference between `StringBuffer` and `StringBuilder`?

    • Answer: Both are mutable strings, but `StringBuffer` is synchronized (thread-safe) while `StringBuilder` is not. `StringBuilder` is generally preferred for better performance in single-threaded environments.
  33. What is an array?

    • Answer: An array is a container object that holds a fixed number of values of a single type. The elements are accessed using their index (starting from 0).
  34. What is a List in Java?

    • Answer: A `List` is an ordered collection of elements that can contain duplicate values. It allows elements to be accessed by their index.
  35. What is a Set in Java?

    • Answer: A `Set` is an unordered collection of elements that does not allow duplicate values.
  36. What is a Map in Java?

    • Answer: A `Map` stores key-value pairs. Each key is unique, and it maps to a specific value. It is used to represent associations between objects.
  37. What is the difference between ArrayList and LinkedList?

    • Answer: `ArrayList` uses an array internally, providing fast access to elements by index but slower insertions and deletions. `LinkedList` uses a doubly linked list, making insertions and deletions fast but slower access by index.
  38. What is a Wrapper class?

    • Answer: Wrapper classes provide a way to convert primitive data types (int, float, boolean, etc.) into objects. This is useful for situations where objects are required, such as using primitives in collections.
  39. What is autoboxing and unboxing?

    • Answer: Autoboxing is the automatic conversion of a primitive type to its corresponding wrapper class object. Unboxing is the reverse process, converting a wrapper class object to its corresponding primitive type.
  40. What is a generic in Java?

    • Answer: Generics allow you to write type-safe code that can work with different data types without losing type information at compile time. They help prevent ClassCastException errors.
  41. What is a Collection in Java?

    • Answer: A `Collection` is a framework that provides an architecture to store and manipulate a group of objects. It's a root interface in the Java Collections Framework.
  42. What are different types of Collections in Java?

    • Answer: The main types include Lists (ordered, allows duplicates), Sets (unordered, no duplicates), and Maps (key-value pairs).
  43. What is an Iterator?

    • Answer: An `Iterator` is an interface that allows you to traverse through the elements of a collection. It provides methods like `hasNext()` and `next()` to iterate through the collection.
  44. What is a Comparator?

    • Answer: A `Comparator` is an interface that defines a method for comparing two objects. It's used to sort collections based on custom criteria.
  45. What is the difference between Comparable and Comparator?

    • Answer: `Comparable` is used to define a natural ordering within a class, while `Comparator` provides a separate mechanism for comparing objects based on different criteria.
  46. Explain multithreading in Java.

    • Answer: Multithreading allows multiple threads to execute concurrently within a single program. This can improve performance by utilizing multiple CPU cores or overlapping I/O operations.
  47. What is a thread?

    • Answer: A thread is a lightweight unit of execution within a program. Multiple threads can run simultaneously, sharing the same memory space.
  48. How do you create a thread in Java?

    • Answer: You can create a thread by extending the `Thread` class or implementing the `Runnable` interface.
  49. What is the difference between extending `Thread` and implementing `Runnable`?

    • Answer: Extending `Thread` is simpler for single-threaded tasks, but implementing `Runnable` allows for multiple inheritance and better design flexibility.
  50. What is thread synchronization?

    • Answer: Thread synchronization is a mechanism to control access to shared resources among multiple threads, preventing race conditions and ensuring data consistency.
  51. What is a deadlock?

    • Answer: A deadlock occurs when two or more threads are blocked indefinitely, waiting for each other to release the resources that they need.
  52. How do you prevent deadlocks?

    • Answer: Techniques include avoiding nested locks, acquiring locks in a consistent order, and using timeouts when acquiring locks.
  53. What is a `volatile` keyword?

    • Answer: The `volatile` keyword ensures that all threads see the most up-to-date value of a variable. It prevents caching of the variable's value in individual threads.
  54. What is `synchronized` keyword?

    • Answer: The `synchronized` keyword ensures that only one thread can access a specific block of code or method at a time. It helps prevent race conditions.
  55. What is a wait() method?

    • Answer: The `wait()` method is used to temporarily suspend a thread's execution until another thread notifies it using `notify()` or `notifyAll()`.
  56. What is a notify() method?

    • Answer: The `notify()` method wakes up a single thread that is waiting on the same object's monitor.
  57. What is a notifyAll() method?

    • Answer: The `notifyAll()` method wakes up all threads that are waiting on the same object's monitor.
  58. What is a JavaBean?

    • Answer: A JavaBean is a reusable software component that follows certain conventions: it has a no-argument constructor, properties (getters and setters), and is serializable.
  59. What is serialization?

    • 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.
  60. What is deserialization?

    • Answer: Deserialization is the reverse process of serialization, converting a byte stream back into an object.
  61. What is the purpose of the `transient` keyword?

    • Answer: The `transient` keyword indicates that a variable should not be serialized. Its value will not be saved when the object is serialized.
  62. What is the difference between a HashSet and a TreeSet?

    • Answer: `HashSet` stores elements in an unordered fashion, while `TreeSet` stores elements in a sorted order (based on natural ordering or a provided comparator).
  63. What is the difference between HashMap and TreeMap?

    • Answer: `HashMap` stores key-value pairs in an unordered fashion, while `TreeMap` stores them in a sorted order (based on the key's natural ordering or a provided comparator).
  64. What is a garbage collector?

    • Answer: A garbage collector is a program that automatically reclaims memory occupied by objects that are no longer referenced by the program.
  65. What is the purpose of the `static` block?

    • Answer: A `static` block is executed once when the class is loaded. It is often used for initializing static variables or performing other class-level initialization tasks.
  66. What is a final keyword?

    • Answer: The `final` keyword can be applied to variables, methods, and classes. When applied to a variable, it makes the variable a constant. When applied to a method, it prevents the method from being overridden in subclasses. When applied to a class, it prevents the class from being inherited.
  67. What is a package in Java?

    • Answer: A package is a way to organize classes and interfaces into a hierarchical structure. It helps avoid naming conflicts and promotes code reusability.
  68. How do you import packages in Java?

    • Answer: You import packages using the `import` keyword followed by the package name (e.g., `import java.util.*;`).
  69. What is an inner class?

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

    • Answer: Types include member inner classes, static nested classes, local inner classes, and anonymous inner classes.
  71. What is an anonymous inner class?

    • Answer: An anonymous inner class is an inner class that is defined without a name. It is often used for short, simple implementations of interfaces or abstract classes.
  72. What is a lambda expression?

    • Answer: A lambda expression is a concise way to represent an anonymous function. It is used to provide implementations for functional interfaces.
  73. What is a functional interface?

    • Answer: A functional interface is an interface that has exactly one abstract method. It can have multiple default methods, but only one abstract method.
  74. What is a stream in Java?

    • Answer: A stream is a sequence of elements from a source, supporting sequential and parallel aggregate operations. Streams provide a declarative way to process collections of data.
  75. What are some common stream operations?

    • Answer: Common operations include `filter()`, `map()`, `reduce()`, `sorted()`, `collect()`, etc.
  76. What is method reference in Java?

    • Answer: A method reference is a shorthand notation for lambda expressions that simply refer to an existing method. It's used to improve code readability.
  77. What is a default method in an interface?

    • Answer: A default method is a method in an interface that has a default implementation. It allows interfaces to evolve without breaking existing implementations.
  78. What is a static method in an interface?

    • Answer: A static method in an interface is a method that belongs to the interface itself, not to any specific implementation. It is called directly using the interface name.
  79. What is a nested class?

    • Answer: A nested class is a class defined within another class. It can be either static or non-static.
  80. Explain the difference between a static nested class and a non-static nested class.

    • Answer: A static nested class doesn't have access to the members of the outer class. A non-static nested class (inner class) has access to the members of the outer class.
  81. What is Java's reflection API?

    • Answer: The Java Reflection API allows you to inspect and modify the runtime behavior of Java programs. You can get information about classes, methods, fields, etc., at runtime.
  82. What is the purpose of the `Class` object?

    • Answer: The `Class` object represents a class at runtime. It provides information about the class's members and allows you to interact with it dynamically.
  83. How do you get a `Class` object?

    • Answer: You can obtain a `Class` object using `Class.forName()`, `object.getClass()`, or the `class` literal (e.g., `String.class`).
  84. What is JDBC?

    • Answer: JDBC (Java Database Connectivity) is an API that allows Java programs to interact with relational databases.
  85. What are the steps involved in connecting to a database using JDBC?

    • Answer: The steps typically involve loading the JDBC driver, establishing a connection using a connection URL, creating a statement, executing SQL queries, processing the results, and closing the connection.
  86. What is a PreparedStatement?

    • Answer: A `PreparedStatement` is a pre-compiled SQL statement that is used to execute the same SQL query multiple times with different parameters. It improves performance and security.
  87. What are some advantages of using PreparedStatement over Statement?

    • Answer: Advantages include improved performance (due to pre-compilation), better security (preventing SQL injection attacks), and easier handling of parameters.
  88. What is an SQL Injection attack?

    • Answer: An SQL Injection attack is a security vulnerability where malicious SQL code is injected into an application's input, allowing attackers to manipulate the database.
  89. How can you prevent SQL Injection attacks?

    • Answer: Using `PreparedStatement` is the primary defense. It parameterizes queries, preventing malicious code from being interpreted as SQL commands.
  90. What is a connection pool?

    • Answer: A connection pool is a mechanism for managing database connections efficiently. It creates a pool of connections that can be reused, reducing the overhead of establishing new connections.
  91. What is a transaction in a database?

    • Answer: A transaction is a sequence of database operations that are treated as a single unit of work. Either all operations succeed, or none do, ensuring data consistency.

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