Java Interview Questions Sorted by Experience Level

Preparing for a Java interview involves mastering a variety of concepts tailored to your experience level. Below is an expanded compilation of common interview questions categorized into junior, mid-level, and senior experience. This comprehensive guide will help you review key topics and ensure you are ready for your next interview.


Junior Level Questions

  1. Name some characteristics of Object-Oriented (OO) programming languages.
  • Key concepts include encapsulation, inheritance, polymorphism, and abstraction.
  1. What are the access modifiers you know? What does each one do?
  • Common modifiers:
    • public: Accessible from anywhere.
    • private: Accessible only within the class.
    • protected: Accessible within the same package and subclasses.
    • package-private (default): Accessible only within the same package.
  1. What is the difference between overriding and overloading a method in Java?
  • Overriding: Same method name and parameters in the subclass (runtime polymorphism).
  • Overloading: Same method name but different parameters in the same class (compile-time polymorphism).
  1. What’s the difference between an Interface and an abstract class?
  • Interfaces can only declare methods (Java 8 introduced default methods), while abstract classes can have method implementations and state.
  1. Can an Interface extend another Interface?
  • Yes, an interface can extend another interface and can extend multiple interfaces.
  1. What does the static keyword mean in Java?
  • It indicates that a method or variable belongs to the class rather than instances of the class. It can be accessed without creating an instance of the class.
  1. Can a static method be overridden in Java?
  • No, static methods are not overridden; they are hidden. The method invoked is determined at compile time.
  1. What is Polymorphism? What about Inheritance?
  • Polymorphism allows methods to do different things based on the object that it is acting upon.
  • Inheritance is a mechanism where one class can inherit fields and methods from another class.
  1. Can a constructor be inherited?
  • No, constructors cannot be inherited. However, a subclass can call the parent class constructor using super().
  1. Do objects get passed by reference or value in Java? Elaborate.
    • Java passes object references by value, meaning the reference itself is passed, but not the object. This allows modifications to the object but not to the reference itself.
  2. What’s the difference between using == and .equals() on a string?
    • == checks for reference equality, while .equals() checks for value equality.
  3. What are hashCode() and equals() used for?
    • They are used for determining object equality and for storing objects in hash-based collections like HashMap. If two objects are equal according to .equals(), they must have the same hashCode().
  4. What does the interface Serializable do? What about Parcelable in Android?
    • Serializable allows Java objects to be serialized for storage or transmission. Parcelable is more efficient for inter-process communication in Android, as it avoids using reflection.
  5. Why are Array and ArrayList different? When would you use each?
    • Arrays have a fixed size and are of a specific type, while ArrayLists are resizable and part of the Java Collections Framework. Use arrays for performance when the size is known and ArrayLists for flexibility.
  6. What’s the difference between an Integer and int?
    • int is a primitive data type, while Integer is a wrapper class that can hold a null value and has methods for conversion and manipulation.
  7. What is a ThreadPool? Is it better than using several “simple” threads?
    • A ThreadPool manages a set of worker threads, improving performance and resource management over creating new threads for every task. It reduces the overhead of thread creation and management.
  8. What’s the difference between local, instance, and class variables?
    • Local variables are defined within a method and can only be accessed there.
    • Instance variables belong to an object, and each object has its own copy.
    • Class variables (static variables) are shared among all instances of a class.
  9. What is the final keyword in Java?
    • The final keyword can be used with classes, methods, and variables:
    • final class: Cannot be subclassed.
    • final method: Cannot be overridden.
    • final variable: Its value cannot be changed after initialization.
  10. How does garbage collection work in Java?
    • Java uses automatic garbage collection to reclaim memory by removing objects that are no longer reachable. The garbage collector runs in the background and manages memory, optimizing resource use.
  11. Explain the concept of an immutable class.
    • An immutable class cannot be changed after it is created. Any modification results in a new instance being created. Examples include the String class and wrapper classes like Integer.

Mid-Level Questions

  1. What is reflection?
  • Reflection is the ability of a program to examine and modify its own structure at runtime. It allows you to inspect classes, methods, fields, and interfaces, and can be used for dynamic method invocation.
  1. What is dependency injection? Can you name a few libraries?
  • Dependency Injection is a design pattern to achieve Inversion of Control. Common libraries include Spring, Guice, and Dagger. It allows for better code modularity and easier testing.
  1. What are strong, soft, and weak references in Java?
  • Strong references prevent garbage collection.
  • Soft references allow the garbage collector to clear them under memory pressure.
  • Weak references are cleared at the next garbage collection cycle, making them suitable for implementing memory-sensitive caches.
  1. What does the keyword synchronized mean?
  • It restricts access to a method or block to a single thread, ensuring thread safety. It can be applied to methods or blocks of code.
  1. Can you have “memory leaks” in Java?
  • Yes, if references to unused objects are retained, they cannot be garbage collected, leading to memory leaks.
  1. Do you need to set references to null in Java/Android?
  • It’s not necessary, but doing so can help the garbage collector reclaim memory in some cases, especially for long-lived objects.
  1. What does it mean to say that a String is immutable?
  • Once a String is created, its value cannot be changed. Any modification creates a new String, which helps with performance in certain scenarios and provides thread safety.
  1. What are transient and volatile modifiers?
  • The transient modifier indicates that a field should not be serialized, while the volatile modifier ensures that changes to a variable are visible to other threads immediately.
  1. What is the finalize() method?
  • It’s a method that is called by the garbage collector before an object is reclaimed, allowing for cleanup operations like closing resources.
  1. How does the try { } finally { } work?
    • The finally block always executes after the try block, regardless of whether an exception occurred, making it suitable for cleanup code.
  2. What is the difference between instantiation and initialization of an object?
    • Instantiation is creating an object from a class, while initialization is setting its state through constructors or setter methods.
  3. When is a static block run?
    • A static block is executed when the class is loaded into memory, before any instances are created.
  4. Why are Generics used in Java?
    • Generics provide type safety, eliminate the need for casting, and allow classes and methods to operate on specified types, improving code reusability.
  5. Can you mention the design patterns you know? Which of those do you normally use?
    • Common patterns include Singleton, Factory, Observer, Strategy, and MVC. The choice depends on the specific problem and design needs.
  6. Can you mention some types of testing you know?
    • Unit testing, integration testing, system testing, acceptance testing, and performance testing.
  7. What is the Observer pattern, and where would you use it?
    • The Observer pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified. It’s often used in GUI applications or event handling systems.
  8. What is the purpose of the transient keyword?
    • The transient keyword is used to indicate that a particular field should not be serialized when the object is converted into a byte stream.
  9. Explain the concept of a Singleton pattern.
    • The Singleton pattern ensures that a class has only one instance and provides a global point of access to it. This is useful for managing shared resources like database connections or configurations.
  10. What is an inner class in Java?
    • An inner class is a class defined within another class. It can access the members of the outer class, including private members, and is used to logically group classes that will only be used in one place.
  11. Explain the use of the volatile keyword in Java.
    • The volatile keyword is used to indicate that a variable’s value will be modified by different threads. It ensures that the most up-to-date value is read from and written to
    the main memory rather than from the thread’s local cache.

Senior-Level Questions

  1. How does Integer.parseInt() work?
  • It converts a String to an int by parsing the string representation of the number and handling exceptions if the string is not a valid representation of an integer.
  1. Do you know what the “double-check locking” problem is?
  • It’s a design pattern that attempts to reduce synchronization overhead when acquiring a lock, but it can lead to issues in a multithreaded environment if not implemented correctly.
  1. Do you know the difference between StringBuffer and StringBuilder?
  • StringBuffer is synchronized and thread-safe, making it slower but safe for use in multithreaded applications. StringBuilder is not synchronized, making it faster for single-threaded operations.
  1. How is a StringBuilder implemented to avoid the immutable string allocation problem?
  • StringBuilder uses a mutable character array to allow modifications without creating new objects for every change, thus optimizing memory usage and performance.
  1. What does Class.forName() do?
  • It dynamically loads a class at runtime based on its name, allowing you to instantiate it or invoke its methods without knowing the class at compile time.
  1. What is Autoboxing and Unboxing?
  • Autoboxing is the automatic conversion of a primitive type to its corresponding wrapper class (e.g., converting int to Integer), while unboxing is the reverse process (e.g., converting Integer to int).
  1. What’s the difference between Enumeration and Iterator?
  • Enumeration is a legacy interface with limited functionality and no support for removing elements, while Iterator provides methods for iteration and safe removal of elements during iteration.
  1. What is the difference between fail-fast and fail-safe in Java?
  • Fail-fast iterators throw a ConcurrentModificationException if the collection is modified during iteration, while fail-safe iterators create a copy of the collection to avoid this issue, allowing iteration to continue safely.
  1. What is PermGen in Java?
  • PermGen (Permanent Generation) is a memory area in the Java heap that stores metadata about classes, methods, and other reflective data. It was removed in Java 8, replaced by Metaspace.
  1. What is a Java priority queue?
    • A priority queue is a type of queue where each element has a priority, and elements are processed based on their priority rather than their order in the queue. It is often implemented using a heap data structure.
  2. Is performance influenced by using the same number in different types: int, Double, and Float?
    • Yes, performance can vary due to the overhead of boxing/unboxing and type conversions. Primitive types (like int and float) are faster than their wrapper classes (like Integer and Double).
  3. What is the Java Heap?
    • The Java heap is a memory area used for dynamic memory allocation, where Java objects are created and managed by the garbage collector. It’s divided into Young, Old (or Tenured), and Permanent areas.
  4. What is a daemon thread?
    • A daemon thread is a low-priority thread that runs in the background to perform tasks such as garbage collection and does not prevent the JVM from exiting when the program finishes executing.
  5. Can a dead thread be restarted?
    • No, once a thread has completed its execution, it cannot be restarted. You need to create a new thread instance for that.
  6. What is the Java Memory Model?
    • The Java Memory Model defines how threads interact through memory and establishes rules for visibility and ordering of variable access, ensuring thread safety and consistency.
  7. What are the differences between Comparable and Comparator interfaces?
    • Comparable defines a natural ordering for objects of a class, while Comparator allows you to define multiple ways to compare objects, providing flexibility in sorting.
  8. What is the purpose of the assert keyword in Java?
    • The assert keyword is used to create assertions, which are statements that test assumptions about the program and can help detect bugs during development.
  9. Explain the concept of multithreading.
    • Multithreading is the concurrent execution of multiple threads in a program. It allows for efficient use of CPU resources and can improve the performance of applications, especially those that are I/O-bound.
  10. What are some common design principles you follow in Java development?
    • Common principles include SOLID principles, DRY (Don’t Repeat Yourself), KISS (Keep It Simple, Stupid), and YAGNI (You Aren’t Gonna Need It).
  11. How do you handle exceptions in Java?
    • Exceptions can be handled using try-catch blocks. You can create custom exceptions, log exceptions for debugging, and finally use the finally block for cleanup operations.

Conclusion

This comprehensive list of interview questions covers a wide range of Java concepts, from basic to advanced levels. Understanding these questions and preparing thoughtful responses will boost your confidence during interviews. Each level builds upon foundational knowledge, so be sure to review the concepts relevant to your experience.

ENJOY LEARNING! 👍👍

Team
Team

This account on Doubtly.in is managed by the core team of Doubtly.

Articles: 480