The Java Interview Prep Handbook – 50 Questions Solved + Code Examples

Vahe Aslanyan

If you're trying to get a job in big tech or you want to refine your skills in software development, a strong grasp of Java is indispensable.

Java is well-known for its robustness in Object-Oriented Programming (OOP), and it provides a comprehensive foundation essential for developers at every level.

This handbook offers a detailed pathway to help you excel in Java interviews. It focuses on delivering insights and techniques relevant to roles in esteemed big tech companies, ensuring you're well-prepared for the challenges ahead.

This guide serves as a comprehensive Java review tutorial, bridging the gap between foundational Java knowledge and the sophisticated expertise sought by industry leaders like Google. And it'll help you deepen your understanding and practical application of Java, preparing you for professional success in the tech industry.

Table of Contents

  • What is Java?
  • What's the difference between the JDK, JRE, and JVM?
  • How does the 'public static void main(String[] args)' method work?
  • What is bytecode in Java?
  • Differentiate between overloading and overriding
  • What is the Java ClassLoader?
  • Can we override static methods in Java?
  • How does the 'finally' block differ from the 'finalize' method in Java?
  • What is the difference between an abstract class and an interface?
  • Explain the concept of Java packages
  • What are Java annotations?
  • How does multi-threading work in Java?
  • Use throw to raise an exception
  • Use throws to declare exceptions
  • What is the significance of the transient keyword?
  • How do you ensure thread safety in Java?
  • Explain the Singleton pattern
  • What are Java Streams?
  • What are the primary differences between ArrayList and LinkedList?
  • How do HashSet, LinkedHashSet, and TreeSet differ?
  • Differentiate between HashMap and ConcurrentHashMap
  • Describe the contract between hashCode() and equals() methods
  • What is Java reflection?
  • How do you create a custom exception in Java?
  • What is the difference between a checked and unchecked exception?
  • What are generics? Why are they used?
  • Explain the concept of Java Lambda Expressions
  • What is the diamond problem in inheritance?
  • Describe the difference between fail-fast and fail-safe iterators
  • What is type erasure in Java generics?
  • Describe the differences between StringBuilder and StringBuffer
  • What is the volatile keyword in Java?
  • Explain the Java memory model
  • What is the purpose of the default keyword in interfaces?
  • How does switch differ in Java 7 and Java 8?
  • Explain the concept of Autoboxing and Unboxing
  • Describe the @FunctionalInterface annotation
  • How can you achieve immutability in Java?
  • What is the decorator pattern?
  • Explain the Java I/O streams
  • How does the garbage collector work in Java?
  • What are the benefits of using Java NIO?
  • Explain the Observer pattern
  • What is the purpose of Java's Optional?
  • Explain Java's try-with-resources
  • Explain the difference between C++ and Java
  • What is polymorphism? Provide an example
  • How can you avoid memory leaks in Java?
  • Explain the purpose of Java's synchronized block
  • Explain the concept of modules in Java

image-23

1. What is Java?

Java is a high-level, object-oriented programming language known for its platform independence. It allows developers to write code once and run it anywhere using the Java Virtual Machine (JVM).

2. What's the Difference between the JDK, JRE, and JVM?

  • JDK (Java Development Kit): This is a software package that provides developers with the tools and utilities necessary to develop, compile, and run Java applications.
  • JRE (Java Runtime Environment): A subset of the JDK, the JRE contains the essential components, including the JVM, to run Java applications but not to develop them.
  • JVM (Java Virtual Machine): An abstract computing machine, the JVM enables Java bytecode to be executed, providing the platform independence Java is known for.

3. How Does the public static void main(String[] args) Method Work?

This method is the entry point for Java applications. The public modifier means it's accessible from other classes, static denotes it's a class-level method, and void indicates it doesn't return any value. The argument String[] args allows command-line arguments to be passed to the application.

4. What is bytecode in Java?

Bytecode is an intermediate, platform-independent code that Java source code is compiled into. It is executed by the JVM, enabling the "write once, run anywhere" capability.

5. Differentiate between overloading and overriding

  • Overloading: This occurs when two or more methods in the same class share the same name but have different parameters. It's a compile-time concept.
  • Overriding: In this case, a subclass provides a specific implementation for a method already defined in its superclass. It's a runtime concept.

image-24

6. What is the Java ClassLoader?

The Java ClassLoader is a part of the JRE that dynamically loads Java classes into the JVM during runtime. It plays a crucial role in Java's runtime environment by extending the core Java classes.

7. Can We Override Static Methods in Java?

No, we cannot override static methods. While a subclass can declare a method with the same name as a static method in its superclass, this is considered method hiding, not overriding.

8. How Does the finally Block Differ from the finalize Method in Java?

Understanding the distinction between the finally block and the finalize method in Java is crucial for effective resource management and exception handling in your programs.

Finally Block:

  • Purpose and Usage: The finally block is a key component of Java's exception handling mechanism. It is used in conjunction with try-catch blocks.
  • Execution Guarantee: Regardless of whether an exception is thrown or caught within the try or catch blocks, the code within the finally block is always executed. This ensures that it runs even if there’s a return statement in the try or catch block.
  • Common Uses: It is typically utilized for cleaning up resources, such as closing file streams, database connections, or releasing any system resources that were acquired in the try block. This helps in preventing resource leaks.

Finalize Method:

  • Definition: The finalize method is a protected method of the Object class in Java. It acts as a final resort for objects garbage collection.
  • Garbage Collector Call: It is called by the garbage collector on an object when the garbage collector determines that there are no more references to the object. However, its execution is not guaranteed, and it's generally unpredictable when, or even if, the finalize method will be invoked.
  • Resource Release: The finalize method is designed to allow an object to clean up its resources before it is collected by the garbage collector. For example, it might be used to ensure that an open file owned by an object is closed.
  • Caution in Use: It's important to note that relying on finalize for resource cleanup is generally not recommended due to its unpredictability and potential impact on performance.

Access Modifiers in Java:

  • Private: This modifier makes a member accessible only within its own class. Other classes cannot access private members of a different class.
  • Default (no modifier): When no access modifier is specified, the member has package-level access. This means it is accessible to all classes within the same package.
  • Protected: A protected member is accessible within its own package and also in subclasses. This is often used in inheritance.
  • Public: Public members are accessible from any class in the Java program. It provides the widest level of access.

Understanding these distinctions and access levels is vital for effective Java programming, ensuring resource management, security, and encapsulation are handled appropriately in your software development endeavors.

9. What is the Difference between an Abstract Class and an Interface?

An abstract class in Java is used as a base for other classes. It can contain both abstract methods (without an implementation) and concrete methods (with an implementation).

Abstract classes can have member variables that can be inherited by subclasses. A class can extend only one abstract class due to Java's single inheritance property.

Example of an Abstract Class:

An interface in Java, on the other hand, is a completely "abstract class" that is used to group related methods with empty bodies.

From Java 8 onwards, interfaces can have default and static methods with a body. A class can implement any number of interfaces.

Example of an Interface:

Both abstract classes and interfaces are foundational concepts in Java, used for achieving abstraction and supporting design patterns like Strategy and Adapter. The use of these concepts depends on the specific requirements and design considerations of your software project.

image-25

10. Explain the Concept of Java Packages

Java packages are a way of organizing and structuring classes and interfaces in Java applications. They provide a means to group related code together. Packages help prevent naming conflicts, enhance code readability, and facilitate code reusability.

For example, consider a banking application. You might have packages like com.bank.accounts , com.bank.customers , and com.bank.transactions . These packages contain classes and interfaces specific to their respective functionalities.

In essence, Java packages are like directories or folders in a file system, organizing code and making it more manageable.

11. What are Java Annotations?

Java annotations are metadata that can be added to Java source code. They provide information about the code to the compiler or runtime environment. Annotations do not directly affect the program's functionality – instead, they convey instructions to tools or frameworks.

A common use of annotations is for marking classes or methods as belonging to a specific framework or for providing additional information to tools like code analyzers, build tools, or even custom code generators.

For example, the @Override annotation indicates that a method is intended to override a method from a superclass, helping catch coding errors during compilation. Another example is @Deprecated , which indicates that a method or class is no longer recommended for use.

12. How Does Multi-threading Work in Java?

Multi-threading in Java allows a program to execute multiple threads concurrently. Threads are lightweight processes within a program that can run independently. Java provides a rich set of APIs and built-in support for multi-threading.

Threads in Java are typically created by either extending the Thread class or implementing the Runnable interface. Once created, threads can be started using the start() method, causing them to run concurrently.

Java's multi-threading model ensures that threads share resources like memory and CPU time efficiently while providing mechanisms like synchronization and locks to control access to shared data.

Multi-threading is useful for tasks such as improving application responsiveness, utilizing multi-core processors, and handling concurrent operations, as often seen in server applications.

13. Use throw to Raise an Exception

In Java programming, the throw keyword is crucial for handling exceptions deliberately and responsively. This approach to exception management allows developers to enforce specific conditions in their code and maintain control over the program flow.

In this example, an IllegalArgumentException is thrown if the age parameter is less than 18. This method of raising an exception ensures that the program behaves predictably under defined conditions, enhancing both the security and reliability of the code.

14. Use throws to Declare Exceptions

The throws keyword in Java serves to declare that a method may cause an exception to be thrown. It signals to the method's caller that certain exceptions might arise, which should be either caught or further declared.

In this scenario, the readDocument method declares that it might throw a FileNotFoundException . This declaration requires the caller of this method to handle this exception, ensuring that appropriate measures are in place to deal with potential errors, and thus improving the robustness of the application.

Both throw and throws are integral to managing exceptions in Java. throw is used for actively raising an exception in the code, while throws declares possible exceptions that a method might produce, thereby mandating their handling by the caller. This distinction is essential for writing error-resistant and well-structured Java programs.

image-26

15. What is the Significance of the transient Keyword?

The transient keyword in Java is used to indicate that a field should not be serialized when an object of a class is converted to a byte stream (for example, when using Java Object Serialization).

This is significant when you have fields in a class that you do not want to include in the serialized form, perhaps because they are temporary, derived, or contain sensitive information.

16. How Do You Ensure Thread Safety in Java?

Thread safety in Java is achieved by synchronizing access to shared resources, ensuring that multiple threads can't simultaneously modify data in a way that leads to inconsistencies or errors.

You can ensure thread safety through synchronization mechanisms like synchronized blocks, using thread-safe data structures, or utilizing concurrent utilities from the java.util.concurrent package.

In the code above, we have a SharedCounter class with a synchronized increment method, ensuring that only one thread can increment the count variable at a time. This synchronization mechanism prevents data inconsistencies when multiple threads access and modify the shared count variable.

We create two threads ( thread1 and thread2 ) that concurrently increment the counter. By using synchronized methods or blocks, we guarantee thread safety, and the final count will be accurate, regardless of thread interleaving.

17. Explain the Singleton Pattern

The Singleton pattern is a design pattern that ensures a class has only one instance and provides a global point of access to that instance. It is achieved by making the constructor of the class private, creating a static method to provide a single point of access to the instance, and lazily initializing the instance when needed.

Implementation without Singleton:

Let's imagine a scenario where you want to establish a database connection. Without the Singleton pattern, every time you'd need a connection, you might end up creating a new one.

Now, imagine initializing this connection multiple times in different parts of your application:

For the above code, "Establishing a new database connection..." would be printed twice, implying two separate connections were created. This is redundant and can be resource-intensive.

Implementation with Singleton:

With the Singleton pattern, even if you attempt to get the connection multiple times, you'd be working with the same instance.

Initializing this connection multiple times:

For the above code, "Establishing a single database connection..." would be printed just once, even though we've called getInstance() twice.

18. What are Java Streams?

Java Streams are a powerful abstraction for processing sequences of elements, such as collections, arrays, or I/O channels, in a functional and declarative style. They provide methods for filtering, mapping, reducing, and performing various transformations on data.

Streams can significantly simplify code and improve readability when working with data collections.

19. What Are the Primary Differences between ArrayList and LinkedList?

ArrayList and LinkedList are both implementations of the List interface. The primary differences between them lie in their internal data structures.

ArrayList uses a dynamic array to store elements, offering fast random access but slower insertions and deletions. LinkedList uses a doubly-linked list, which provides efficient insertions and deletions but slower random access.

image-27

20. How do HashSet , LinkedHashSet , and TreeSet Differ?

  • HashSet stores elements in an unordered manner, offering constant-time complexity for basic operations.
  • LinkedHashSet maintains the order of insertion, providing ordered iteration of elements.
  • TreeSet stores elements in a sorted order (natural or custom), offering log(n) time complexity for basic operations.

In this code, we add a large number of elements to each type of set ( HashSet , LinkedHashSet , and TreeSet ) and measure the time it takes to perform this operation. This demonstrates the performance characteristics of each set type.

Typically, you will observe that HashSet performs the fastest for adding elements since it doesn't maintain any specific order, followed by LinkedHashSet , and TreeSet , which maintains a sorted order.

This output demonstrates the time taken (in nanoseconds) to add one million elements to each of the three sets: HashSet , LinkedHashSet , and TreeSet . As you can see, HashSet is the fastest, followed by LinkedHashSet , and TreeSet is the slowest due to its need to maintain elements in sorted order.

21. Differentiate between HashMap and ConcurrentHashMap

HashMap is not thread-safe and is suitable for single-threaded applications. ConcurrentHashMap , on the other hand, is designed for concurrent access and supports multiple threads without external synchronization. It provides high concurrency and performance for read and write operations.

22. Describe the Contract between the hashCode() and equals() Methods

The contract between hashCode() and equals() methods states that if two objects are equal ( equals() returns true), their hash codes ( hashCode() ) must also be equal.

However, the reverse is not necessarily true: objects with equal hash codes may not be equal. Adhering to this contract is crucial when using objects as keys in hash-based collections like HashMap .

23. What is Java Reflection?

Java reflection is a feature that allows you to inspect and manipulate the metadata of classes, methods, fields, and other program elements at runtime. It enables you to perform tasks such as dynamically creating objects, invoking methods, and accessing fields, even for classes that were not known at compile time.

24. How Do You Create a Custom Exception in Java?

You can create a custom exception in Java by extending the Exception class or one of its subclasses. By doing so, you can define your exception with specific attributes and behaviors tailored to your application's needs.

image-28

25. What is the Difference between a Checked and Unchecked Exception?

Checked exceptions are exceptions that must be either caught using a try-catch block or declared in the method signature using the throws keyword.

Unchecked exceptions (usually subclasses of RuntimeException ) do not require such handling.

Checked exceptions are typically used for recoverable errors, while unchecked exceptions represent programming errors or runtime issues.

Here is a code example to illustrate checked and unchecked exceptions.

In this code, we attempt to read a file using FileReader, which may throw a checked exception called IOException .

To handle this exception, we enclose the file reading code in a try-catch block specifically catching IOException . This is an example of how you handle checked exceptions, which are typically used for recoverable errors like file not found or I/O issues.

Now, let's take a look at an example of an unchecked exception:

In this code, we attempt to divide an integer by zero, which leads to an unchecked exception called ArithmeticException . Unchecked exceptions do not require explicit handling using a try-catch block. However, it's good practice to catch and handle them when you anticipate such issues. These exceptions often represent programming errors or runtime issues.

26. What Are Generics? Why Are They Used?

Generics in Java are a powerful feature that allows you to create classes, interfaces, and methods that operate on types. They provide a way to define classes or methods with a placeholder for the data type that will be used when an instance of the class is created or when a method is called.

Generics are used to make your code more reusable, type-safe, and less error-prone by allowing you to write generic algorithms that work with different data types. They help eliminate the need for typecasting and enable compile-time type checking.

For example, consider the use of a generic class to create a List of integers:

Generics ensure that you can only add integers to the list and that you don't need to perform explicit typecasting when retrieving elements from the list.

27. Explain the Concept of Java Lambda Expressions

Lambda expressions in Java are a concise way to express instances of single-method interfaces (functional interfaces) using a more compact syntax. They facilitate functional programming by allowing you to treat functions as first-class citizens.

Lambda expressions consist of a parameter list, an arrow (->), and a body. They provide a way to define and use anonymous functions.

For example, consider a functional interface Runnable that represents a task to be executed. With a lambda expression, you can define and execute a runnable task as follows:

We will talk about a more practical example later down the post.

28. What is the Diamond Problem in Inheritance?

The diamond problem in inheritance is a common issue in object-oriented programming languages that support multiple inheritance. It occurs when a class inherits from two classes that have a common ancestor class, resulting in ambiguity about which superclass's method or attribute to use.

Java solves the diamond problem by not supporting multiple inheritance of classes (that is, a class cannot inherit from more than one class).

But Java allows multiple inheritance of interfaces, which doesn't lead to the diamond problem because interfaces only declare method signatures, and the implementing class must provide concrete implementations. In case of method conflicts, the implementing class must explicitly choose which method to use.

Here's a simplified example to illustrate the diamond problem (even though Java doesn't directly encounter it):

In Java, the diamond problem is avoided through interface implementation and explicit method choice when conflicts arise.

29. Describe the Difference between Fail-fast and Fail-safe Iterators

In Java, fail-fast and fail-safe are two strategies for handling concurrent modification of collections during iteration.

Fail-fast iterators throw a ConcurrentModificationException if a collection is modified while being iterated. Fail-safe iterators, on the other hand, do not throw exceptions and allow safe iteration even if the collection is modified concurrently.

Fail-Fast Iterator Example:

In this example, when we attempt to remove an element from the list while iterating, it leads to a ConcurrentModificationException , which is characteristic of fail-fast behavior. Fail-fast iterators immediately detect and throw an exception when they detect that the collection has been modified during iteration.

Fail-Safe Iterator Example:

In this example, a ConcurrentHashMap is used, which supports fail-safe iterators. Even if we modify the map concurrently while iterating, there is no ConcurrentModificationException thrown. Fail-safe iterators continue iterating over the original elements and do not reflect changes made after the iterator is created.

image-29

30. What is Type Erasure in Java Generics?

Type erasure is a process in Java where type parameters in generic classes or methods are replaced with their upper bound or Object during compilation. This erasure ensures backward compatibility with pre-generic Java code. But it means that the type information is not available at runtime, which can lead to issues in some cases.

31. Describe the Differences between StringBuilder and StringBuffer

Thread safety:.

StringBuffer is thread-safe. This means it is synchronized, so it ensures that only one thread can modify it at a time. This is crucial in a multithreaded environment where you have multiple threads modifying the same string buffer.

StringBuilder , on the other hand, is not thread-safe. It does not guarantee synchronization, making it unsuitable for use in scenarios where a string is accessed and modified by multiple threads concurrently. But this lack of synchronization typically leads to better performance under single-threaded conditions.

Performance:

Because StringBuffer operations are synchronized, they involve a certain overhead that can impact performance negatively when high-speed string manipulation is required.

StringBuilder is faster than StringBuffer because it avoids the overhead of synchronization. It's an excellent choice for string manipulation in a single-threaded environment.

Use Case Scenarios:

Use StringBuffer when you need to manipulate strings in a multithreaded environment. Its thread-safe nature makes it the appropriate choice in this scenario.

Use StringBuilder in single-threaded situations, such as local method scope or within a block synchronized externally, where thread safety is not a concern. Its performance benefits shine in these cases.

API Similarity:

Both StringBuilder and StringBuffer have almost identical APIs. They provide similar methods for manipulating strings, such as append() , insert() , delete() , reverse() , and so on.

This similarity means that switching from one to the other in your code is generally straightforward.

Memory Efficiency:

Both classes are more memory efficient compared to using String for concatenation. Since String is immutable in Java, concatenation with String creates multiple objects, whereas StringBuilder and StringBuffer modify the string in place.

Introduced Versions:

StringBuffer has been a part of Java since version 1.0, whereas StringBuilder was introduced later in Java 5. This introduction was primarily to offer a non-synchronized alternative to StringBuffer for improved performance in single-threaded applications.

You should make the choice between StringBuilder and StringBuffer based on the specific requirements of your application, particularly regarding thread safety and performance needs.

While StringBuffer provides safety in a multithreaded environment, StringBuilder offers speed and efficiency in single-threaded or externally synchronized scenarios.

32. What is the volatile Keyword in Java?

Basic Definition: The volatile keyword is used to modify the value of a variable by different threads. It ensures that the value of the volatile variable will always be read from the main memory and not from the thread's local cache.

Visibility Guarantee: In a multithreading environment, threads can cache variables. Without volatile, there's no guarantee that one thread's changes to a variable will be visible to another. The volatile keyword guarantees visibility of changes to variables across threads.

Happens-Before Relationship: volatile establishes a happens-before relationship in Java. This means that all the writes to the volatile variable are visible to subsequent reads of that variable, ensuring a consistent view of the variable across threads.

Usage Scenarios: volatile is used for variables that may be updated by multiple threads. It's often used for flags or status variables. For example, a volatile boolean running variable can be used to stop a thread.

Limitations: Volatile cannot be used with class or instance variables. It's only applicable to fields. It doesn't provide atomicity.

For instance, volatile int i; i++; is not an atomic operation. For atomicity, you might need to resort to AtomicInteger or synchronized methods or blocks. It's not a substitute for synchronization in every case, especially when multiple operations on the volatile variable need to be atomic.

Avoiding Common Misconceptions: A common misconception is that volatile makes the whole block of statements atomic, which is not true. It only ensures the visibility and ordering of the writes to the volatile variable.

Another misconception is that volatile variables are slow. But while they might have a slight overhead compared to non-volatile variables, they are generally faster than using synchronized methods or blocks. Performance Considerations: volatile can be a more lightweight alternative to synchronization in cases where only visibility concerns are present. It doesn't incur the locking overhead that synchronized methods or blocks do. Best Practices: Use volatile sparingly and only when necessary. Overusing it can lead to memory visibility issues that are harder to detect and debug. Always assess whether your use case requires atomicity, in which case other concurrent utilities or synchronization might be more appropriate.

volatile use case:

We will create a simple program where one thread modifies a volatile boolean flag, and another thread reads this flag. This flag will be used to control the execution of the second thread.

Code Example:

Key points in the comments:.

  • Visibility of volatile variable: The most crucial aspect of using volatile here is ensuring that the update to the running variable in one thread (main thread) is immediately visible to another thread ( thread1 ). This is what allows thread1 to stop gracefully when running is set to false .
  • Use in a Simple Flag Scenario: The example demonstrates a common scenario for using volatile , that is as a simple flag to control the execution flow in a multithreaded environment.
  • Absence of Compound Operations: Note that we are not performing any compound operations (like incrementing) on the running variable. If we were, additional synchronization would be needed because volatile alone does not guarantee atomicity of compound actions.
  • Choice of volatile Over Synchronization: The choice to use volatile over other synchronization mechanisms (like synchronized blocks or Locks ) is due to its lightweight nature when dealing with the visibility of a single variable. It avoids the overhead associated with acquiring and releasing locks.

33. Explain the Java Memory Model

The JMM defines how Java threads interact through memory. Essentially, it describes the relationship between variables and the actions of threads (reads and writes), ensuring consistency and predictability in concurrent programming.

Happens-Before Relationship:

At the heart of the JMM is the 'happens-before' relationship. This principle ensures memory visibility, guaranteeing that if one action happens-before another, then the first is visible to and affects the second.

For example, changes to a variable made by one thread are guaranteed to be visible to other threads only if a happens-before relationship is established.

Memory Visibility:

Without the JMM, threads might cache variables, and changes made by one thread might not be visible to others. The JMM ensures that changes made to a shared variable by one thread will eventually be visible to other threads.

Synchronization:

The JMM utilizes synchronization to establish happens-before relationships. When a variable is accessed within synchronized blocks, any write operation in one synchronized block is visible to any subsequent read operation in another synchronized block.

Additionally, the JMM governs the behavior of volatile variables, ensuring visibility of updates to these variables across threads without synchronization.

Thread Interleaving and Atomicity:

The JMM defines how operations can interleave when executed by multiple threads. This can lead to complex states if not managed correctly.

Atomicity refers to operations that are indivisible and uninterrupted. In Java, operations on most primitive types (except long and double ) are atomic. However, compound operations (like incrementing a variable) are not automatically atomic.

Reordering:

The JMM allows compilers to reorder instructions for performance optimization as long as happens-before guarantees are maintained. However, this can lead to subtle bugs if not properly understood.

Use of Volatile Keyword:

The volatile keyword plays a significant role in the JMM. It ensures that any write to a volatile variable establishes a happens-before relationship with subsequent reads of that variable, thus ensuring memory visibility without the overhead of synchronization.

Locking Mechanisms:

Locks in Java (implicit via synchronized blocks/methods or explicit via ReentrantLock or others) also adhere to the JMM, ensuring that memory visibility is maintained across threads entering and exiting locks.

Safe Publication:

The JMM also addresses the concept of safe publication, ensuring that objects are fully constructed and visible to other threads after their creation.

High-Level Implications:

Understanding the JMM is critical for writing correct and efficient multi-threaded Java applications. It helps developers reason about how shared memory is handled, especially in complex applications where multiple threads interact and modify shared data.

Best Practices:

  • Always use the appropriate synchronization mechanism to ensure memory visibility and atomicity.
  • Be cautious about memory visibility issues; even simple operations can lead to visibility problems in a multi-threaded context.
  • Understand the cost of synchronization and use volatile variables where appropriate.

34. What is the Purpose of the default Keyword in Interfaces?

The default keyword in Java interfaces, introduced in Java 8, marks a significant evolution in the Java language, especially in how interfaces are used and implemented. It serves several key purposes:

Adding Method Implementations in Interfaces:

Prior to Java 8, interfaces in Java could only contain method signatures (abstract methods) without any implementation.

The default keyword allows you to provide a default implementation for a method within an interface. This feature bridges a gap between full abstraction (interfaces) and concrete implementations (classes).

Enhancing Interface Evolution:

One of the primary motivations for introducing the default keyword was to enhance the evolution of interfaces.

Before Java 8, adding a new method to an interface meant breaking all its existing implementations. With default methods, you can add new methods to interfaces with default implementations without breaking the existing implementations.

This is particularly useful for library designers, ensuring backward compatibility when interfaces need to be expanded.

Facilitating Functional Programming:

\The introduction of default methods played a crucial role in enabling functional programming features in Java, such as Lambda expressions. It allowed for richer interfaces (like java.util.stream.Stream ) which are fundamental to functional-style operations in Java.

Multiple Inheritance of Behavior:

While Java does not allow multiple inheritance of state (that is, you cannot inherit from multiple classes), the default keyword enables multiple inheritance of behavior.

A class can implement multiple interfaces, and each interface can provide a default implementation of methods, which the class inherits.

Reducing Boilerplate Code:

default methods can be used to reduce the amount of boilerplate code by providing a general implementation that can be shared across multiple implementing classes, while still allowing individual classes to override the default implementation if a more specific behavior is required.

Example Usage:

In this example, any class implementing the Vehicle interface must provide an implementation for cleanVehicle , but it's optional for startEngine . The default implementation of startEngine can be used as is, or overridden by the implementing class.

Best Practices and Considerations:

  • Use Sparingly: Default methods should be used judiciously. They are best suited for gradually evolving interfaces or for methods that have a common implementation across most implementing classes.
  • Design With Care: When designing interfaces with default methods, consider how they might be used or overridden. It's important to document the expected behavior and interactions between default methods and other abstract methods in the interface.
  • Overriding Default Methods: Just like any inherited method, default methods can be overridden in the implementing class. This should be done to provide a specific behavior different from the default implementation.

image-30

35. How Does switch Differ in Java 7 and Java 8?

Limited Case Types: In Java 7, the switch statement supports limited types for the case labels, namely byte , short , char , int , and their corresponding Wrapper classes, along with enum types and, as of Java 7, String .

Traditional Structure: The structure of the switch statement in Java 7 follows the conventional C-style format, with a series of case statements and an optional default case. Each case falls through to the next unless it ends with a break statement or other control flow statements like return .

No Lambda Expressions: Java 7 does not support lambda expressions, and thus, they cannot be used within a switch statement or case labels.

Lambda Expressions: While the basic syntax and supported types for the switch statement itself did not change in Java 8, the introduction of lambda expressions in this version brought a new paradigm in handling conditional logic.

This doesn’t directly change how switch works, but it offers alternative patterns for achieving similar outcomes, especially when used in conjunction with functional interfaces.

Functional Programming Approach: Java 8 promotes a more functional programming style, encouraging the use of streams, lambda expressions, and method references. This can lead to alternatives for traditional switch statements, like using Map of lambdas for conditional logic, which can be more readable and concise.

Enhanced Readability and Maintainability: Although not a direct change to the switch statement, the use of lambda expressions and functional programming practices in Java 8 can lead to more readable and maintainable code structures that might otherwise use complex switch or nested if-else statements.

Practical Considerations:

  • When to Use switch in Java 8: Despite the advancements in Java 8, the switch statement remains a viable and efficient method for controlling complex conditional logic. It is particularly useful when dealing with a known set of possible values, such as enum constants or strings.
  • Combining switch with Lambdas: While you cannot use lambdas directly in a switch statement, Java 8 allows for more elegant ways to handle complex conditional logic that might traditionally have been a use case for switch . For example, using a Map with lambdas or method references can sometimes replace a complex switch statement.
  • Performance Considerations: The performance of a switch statement is generally better than a series of if-else statements, especially when dealing with a large number of cases, due to its internal implementation using jump tables or binary search.

36. Explain the Concept of Autoboxing and Unboxing

What is autoboxing.

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer , a double to a Double , and so on.

When to use autoboxing

This feature is commonly used when working with collections, like ArrayList or HashMap , which can only store objects and not primitive types.

It simplifies the code by allowing direct assignment of a primitive value to a variable of the corresponding wrapper class.

Behind the Scenes:

When autoboxing, the compiler essentially uses the valueOf method of the respective wrapper class to convert the primitive to its wrapper type.

For example, Integer.valueOf(int) is used for converting int to Integer .

Performance Considerations:

  • While convenient, autoboxing can introduce performance overhead, especially in scenarios with extensive boxing and unboxing in tight loops, due to the creation of additional objects.

What is unboxing?

Unboxing is the reverse process, where the Java compiler automatically converts an object of a wrapper type to its corresponding primitive type.

When to use unboxing

It is often used when performing arithmetic operations or comparisons on objects of wrapper classes, where primitive types are required.

During unboxing, the compiler uses the corresponding wrapper class's method to extract the primitive value. For instance, it uses Integer.intValue() to get the int from an Integer .

Null Pointer Exception:

A crucial point to consider is that unboxing a null object reference will throw a NullPointerException . This is a common bug in code that relies heavily on autoboxing and unboxing.

  • Be Aware of Implicit Conversions: It's important to be aware that these conversions are happening, as they can sometimes lead to unexpected behavior, especially with regards to NullPointerExceptions during unboxing of null references.
  • Consider Performance: In performance-sensitive applications, prefer using primitives to avoid the overhead of autoboxing and unboxing.
  • Null Safety: Always check for null before unboxing, to avoid potential NullPointerExceptions .
  • Readability vs Efficiency: While autoboxing and unboxing significantly improve code readability and reduce boilerplate, be mindful of their impact on performance and choose wisely based on the application's context.

37. Describe the @FunctionalInterface Annotation

The @FunctionalInterface annotation in Java is a key feature that dovetails with the language's embrace of functional programming concepts, particularly since Java 8. It serves a specific purpose in defining and enforcing certain coding patterns, making it a vital tool for developers focusing on functional-style programming.

Definition and Purpose

@FunctionalInterface is an annotation that marks an interface as a functional interface.

A functional interface in Java is an interface that contains exactly one abstract method. This restriction makes it eligible to be used in lambda expressions and method references, which are core components of Java's functional programming capabilities.

Enforcing Single Abstract Method

The primary role of @FunctionalInterface is to signal the compiler to enforce the rule of a single abstract method. If the annotated interface does not adhere to this rule, the compiler throws an error, ensuring the interface's contract is not accidentally broken by adding additional abstract methods.

Usage and Implications:

  • Lambda Expressions: Functional interfaces provide target types for lambda expressions and method references. For example, Java's standard java.util.function package contains several functional interfaces like Function<T,R> , Predicate<T> , Consumer<T> , which are widely used in stream operations and other functional programming scenarios.
  • Optional but Recommended: While the @FunctionalInterface annotation is not mandatory for an interface to be considered a functional interface by the Java compiler, using it is considered best practice. It makes the developer's intention clear and ensures the contract of the functional interface is not inadvertently broken.
  • Existing Interfaces: Many existing interfaces from earlier versions of Java naturally fit the definition of a functional interface. For example, java.lang.Runnable and java.util.concurrent.Callable are both functional interfaces as they have only one abstract method.

In this example, SimpleFunction is a functional interface with one abstract method execute() . The @FunctionalInterface annotation ensures that no additional abstract methods are inadvertently added.

  • Clarity and Documentation: Use @FunctionalInterface to communicate your intention clearly both to the compiler and to other developers. It serves as a form of documentation.
  • Design with Care: When designing a functional interface, consider its general utility and how it fits into the broader application architecture, especially if it's intended to be used across different parts of the application.
  • Avoid Overuse: While functional programming in Java can lead to more elegant and concise code, be cautious of overusing lambdas and functional interfaces, as they can make the code harder to read and debug if used excessively or inappropriately.
  • Compatibility with Older Java Versions: Be aware that @FunctionalInterface is a Java 8 feature. If you're working on applications that need to be compatible with earlier Java versions, you won’t be able to use this feature.

38. How Can You Achieve Immutability in Java?

Achieving immutability in Java is a fundamental practice, particularly useful for creating robust, thread-safe applications.

An immutable object is one whose state cannot be modified after it is created. Here's a detailed and precise explanation of how to achieve immutability in Java:

Core Principles of Immutability:

  • No Setters: Immutable objects do not expose any methods to modify their state after construction. This typically means not providing any setter methods.
  • Final Class: The class should be declared as final to prevent subclassing. Subclasses could add mutable state, undermining the immutability of the parent class.
  • Final Fields: All fields should be final , ensuring they are assigned only once, typically within the constructor, and cannot be re-assigned.
  • Private Fields: Fields should be private to prevent external modification and to encapsulate the data.
  • No Direct Access to Mutable Objects:
  • If your class has fields that are references to mutable objects (like arrays or collections), ensure these fields are not directly exposed or modified:
  • Do not provide methods that modify mutable objects.
  • Do not share references to the mutable objects. Provide copies of mutable objects when needed.

How to Create an Immutable Class:

  • Defensive Copies: When dealing with mutable objects passed to the constructor or returned by methods, create defensive copies. This practice prevents external code from modifying the internal state of the immutable object.
  • Immutable Collections: Utilize immutable collections (like those provided in Java 9 and later) to simplify the creation of classes with immutable collection fields.
  • Performance Considerations: Be mindful of the performance implications of creating defensive copies, especially in performance-critical applications.
  • Use in Multi-threaded Environments: Immutable objects are inherently thread-safe, making them ideal for use in multi-threaded environments.
  • String and Wrapper Types: Leverage the immutability of String and wrapper types (Integer, Long, and so on) as part of your immutable objects.
  • Design Strategy: Consider immutability as a design strategy, especially for objects representing values that are not expected to change, such as configuration data, constants, or natural data types.

Advantages of Immutability:

  • Simplicity and Clarity: Immutable objects are easier to understand and use. There's no need to track changes in state, reducing cognitive load.
  • Thread Safety: Immutability eliminates issues related to concurrency and synchronization, as immutable objects can be freely shared between threads without synchronization.
  • Caching and Reuse: Immutable objects can be cached and reused, as they are guaranteed not to change, reducing the overhead of object creation.
  • Hashcode Caching: Immutable objects are great candidates for caching their hashcode, which can be beneficial in collections like HashMaps and HashSets .

39. What is the Decorator Pattern?

The Decorator Pattern is a structural design pattern used in object-oriented programming, and it's particularly useful for extending the functionality of objects at runtime. It is a robust alternative to subclassing, providing a more flexible approach to add responsibilities to objects without modifying their underlying classes.

Purpose of decorator pattern

The Decorator Pattern allows you to attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

The pattern involves a set of decorator classes that are used to wrap concrete components. Each decorator class has a reference to a component object and adds its own behavior either before or after delegating the task to the component object.

How to implement the decorator pattern

It typically involves an abstract decorator class that implements or extends the same interface or superclass as the objects it will dynamically add functionality to. Concrete decorators then extend the abstract decorator.

Key Components:

  • Component: An interface or abstract class defining the operations that can be altered by decorators.
  • Concrete Component: A class implementing or extending the Component, defining an object to which additional responsibilities can be attached.
  • Decorator: An abstract class that extends or implements the Component interface and has a reference to a Component.
  • Concrete Decorator: A class that extends the Decorator and adds functionalities to the Component it decorates.

Decorator example in Java:

Usage and advantages:.

  • Flexibility: The Decorator Pattern provides a more flexible way to add responsibilities to objects compared to subclassing. New functionalities can be added at runtime.
  • Avoid Class Explosion: It helps in avoiding an extensive hierarchy of subclasses when you need multiple combinations of functionalities.
  • Single Responsibility Principle: Decorators allow functionalities to be divided into simple classes with single responsibilities.

Considerations:

  • Complexity: Overuse of the decorator pattern can lead to complexity, making the code harder to understand and maintain.
  • Instantiation Management: Managing the instantiation of decorated objects can be challenging, especially when dealing with multiple layers of decoration.

The Decorator Pattern is a powerful tool in a software developer's toolkit, offering a dynamic and flexible solution for extending object functionality. Understanding and applying this pattern can greatly enhance the design of software, particularly in situations where adding responsibilities to objects at runtime is necessary.

This pattern is highly valued in software development, as it showcases an ability to effectively manage and extend object functionalities without altering existing codebases, aligning with principles of maintainability and scalability.

40. Explain Java I/O Streams

Java I/O (Input/Output) streams are a fundamental part of the Java I/O API, providing a robust framework for handling input and output operations in Java. Understanding these streams is crucial for efficient data handling in Java applications.

Overview of Java I/O Streams

I/O streams in Java are used to read data from an input source and to write data to an output destination. The Java I/O API is rich and provides various classes to handle different types of data, like bytes, characters, objects, etc.

Stream Types:

Java I/O streams are broadly categorized into two types:

  • Byte Streams: Handle I/O of raw binary data.
  • Character Streams: Handle I/O of character data, automatically handling character encoding and decoding.

Byte Streams:

  • Classes: InputStream and OutputStream are abstract classes at the hierarchy's root for byte streams.
  • Usage: They are used for reading and writing binary data, such as image or video files.
  • Example Classes: FileInputStream , FileOutputStream , BufferedInputStream , BufferedOutputStream , etc.

Character Streams:

  • Classes: Reader and Writer are abstract classes for character streams.
  • Usage: Suitable for handling textual data, ensuring correct interpretation of characters according to the default character encoding.
  • Example Classes: FileReader , FileWriter , BufferedReader , BufferedWriter , etc.

Key Features of Java I/O Streams:

  • Stream Hierarchy: Java uses a hierarchy of classes to manage different types of I/O operations, allowing for flexibility and reusability of code.
  • Decorators: Java I/O uses decorators, where one stream wraps another and adds additional capabilities, like buffering, data conversion, and so on.
  • Buffering: Buffering is a common practice in I/O streams to enhance I/O efficiency, allowing for the temporary storage of data in memory before it's written to or read from the actual I/O source.
  • Exception Handling: I/O operations in Java are prone to errors like file not found, access denied, etc. Hence, most I/O operations throw IOException , which must be properly handled using try-catch blocks or thrown further.
  • Use Buffered Streams: Always use buffered streams ( BufferedInputStream , BufferedOutputStream , BufferedReader , BufferedWriter ) for efficient I/O operations, as they reduce the number of actual I/O operations by buffering chunks of data.
  • Close Streams: Ensure streams are closed after their operation is complete to free up system resources. This is typically done in a finally block or using try-with-resources introduced in Java 7.
  • Error Handling: Implement robust error handling. I/O operations are susceptible to many issues, so proper exception handling is crucial.
  • Character Encoding: Be mindful of character encoding while using character streams. Incorrect handling of encoding can lead to data corruption.

Practical Example:

In this example, BufferedReader and BufferedWriter are used for reading from and writing to a text file, demonstrating the use of character streams with buffering for efficiency.

Java I/O streams form the backbone of data handling in Java applications. Understanding the distinction between byte and character streams, along with the proper use of buffering and exception handling, is essential for writing efficient, robust, and maintainable Java code.

This knowledge is vital for Java developers and is often a subject of interest in technical interviews, showcasing one's capability to handle data proficiently in Java applications.

image-31

41. How Does the Garbage Collector Work in Java?

In Java, garbage collection (GC) is a critical process of automatically freeing memory by reclaiming space from objects that are no longer in use, ensuring efficient memory management.

Understanding how the garbage collector works in Java is essential for writing high-performance applications and is a key area of knowledge in professional Java development.

Overview of Garbage Collection in Java

The primary function of garbage collection in Java is to identify and discard objects that are no longer needed by a program. This prevents memory leaks and optimizes memory usage.

Automatic Memory Management

Unlike languages where memory management is manual (like C/C++), Java provides automatic memory management through its garbage collector, which runs in the background.

How the Garbage Collector Works

Object creation and heap storage:.

In Java, objects are created in a heap memory area. This heap is divided into several parts – Young Generation, Old Generation (or Tenured Generation), and Permanent Generation (replaced by Metaspace in Java 8).

  • Young Generation: Newly created objects reside in the Young Generation, which is further divided into three parts: one Eden space and two Survivor spaces (S0 and S1). Most objects die young. When the Eden space fills up, a minor GC is triggered, moving surviving objects to one of the Survivor spaces (S0 or S1) and clearing Eden.
  • Aging of Objects: As objects survive more garbage collection cycles, they age. After surviving certain cycles, they are moved to the Old Generation.
  • Old Generation: The Old Generation stores long-living objects. A more comprehensive form of GC, known as major GC, occurs here, which is generally more time-consuming.
  • Metaspace (Java 8 and above): Metaspace stores metadata of classes. Unlike the PermGen (Permanent Generation) space in earlier Java versions, Metaspace uses native memory, and its size is not fixed but can be configured.

Types of Garbage Collectors in Java:

  • Serial GC: Suitable for single-threaded environments. It freezes all application threads during garbage collection.
  • Parallel GC: Also known as Throughput Collector, it uses multiple threads for young generation garbage collection but stops all application threads during major GC.
  • Concurrent Mark Sweep (CMS) GC: Minimizes pauses by doing most of its work concurrently with application threads but requires more CPU resources.
  • G1 Garbage Collector: Designed for large heap memory areas, it divides the heap into regions and prioritizes GC on regions with the most garbage first.

Garbage Collection Processes

The process starts by marking all reachable objects. Reachable objects are those that are accessible directly or indirectly through references from root objects (like local variables, static fields, etc.).

Unreachable objects (those not marked as reachable) are considered for deletion .

To prevent fragmentation and optimize memory usage, some garbage collectors perform compaction , moving surviving objects closer together.

  • Avoid Memory Leaks: Despite automatic garbage collection, memory leaks can still occur (for example, through static references). It's crucial to be mindful of object references and their lifecycles.
  • GC Tuning: For high-performance applications, GC tuning can be essential. Understanding different garbage collector types and their configuration parameters allows for optimal tuning according to application needs.
  • Monitoring and Profiling: Regular monitoring of garbage collection and memory usage is important, especially for applications with high throughput or large heaps.

Garbage collection in Java is a sophisticated system designed to efficiently manage memory in the Java Virtual Machine (JVM). An in-depth understanding of how garbage collection works, its types, and its impact on application performance is essential for Java developers, particularly those working on large-scale, high-performance applications.

This knowledge not only helps in writing efficient and robust applications but also is a valuable skill in troubleshooting and performance tuning, aspects highly regarded in the field of software development.

42. What Are the Benefits of Using Java NIO?

Java NIO (New Input/Output), introduced in JDK 1.4, marks a substantial advancement in Java's approach to I/O operations. It was developed to address the constraints of traditional I/O methods, leading to improved scalability and efficiency.

This makes Java NIO particularly advantageous in scenarios demanding high throughput and concurrent access.

Let’s discuss the key benefits of using Java NIO in detail.

1. Channels and Buffers: Enhanced Data Handling

  • Channels : These are bi-directional conduits allowing both reading and writing operations. Unlike traditional unidirectional streams, channels simplify I/O patterns, especially for network sockets, by enabling two-way communication within a single channel.
  • Buffers : Acting as fixed-size data containers, buffers allow batch processing of data. This is more efficient compared to the byte-by-byte processing in traditional I/O, as it enables handling data in larger, more manageable blocks.

2. Non-blocking and Asynchronous I/O

Java NIO supports non-blocking and asynchronous I/O operations, a stark contrast to the blocking nature of traditional I/O where a thread remains idle until an operation completes.

This feature of NIO means a thread can initiate an I/O operation and continue performing other tasks without waiting for the I/O process to finish. This capability significantly enhances the scalability and responsiveness of applications, making them more efficient in handling multiple concurrent I/O requests.

3. Practical Applications

Java NIO is particularly effective in environments that require high-performance and low latency, such as:

  • Web and Application Servers : Managing high-volume network traffic efficiently.
  • Real-time Systems : Like trading platforms where quick data processing is critical.
  • Big Data Applications : Benefiting from efficient handling of large datasets.
  • File-based Database Systems : Where efficient file I/O operations are crucial.

4. Channels: The Foundation of NIO’s Architecture

Channels serve as the backbone of NIO, providing a more unified and simplified interface for various I/O operations. They come in different types, each catering to specific needs:

  • FileChannel : For file operations.
  • SocketChannel and ServerSocketChannel : For TCP network communications.
  • DatagramChannel : For UDP operations.
  • Pipes : For inter-thread communication. Particularly in network operations, the ability of channels to operate in a non-blocking mode allows a single thread to handle multiple connections, enhancing the application’s scalability.

5. Buffers: Central to NIO’s Data Transfer

Buffers in NIO are essential for data transfer, acting as temporary storage for data during I/O operations. Their key operations include:

  • Put and Get : For writing and reading data.
  • Flip : To switch modes between reading and writing.
  • Clear and Compact : Preparing the buffer for new data. Different buffer types (like ByteBuffer, CharBuffer, IntBuffer) cater to various data primitives, enhancing the flexibility and efficiency of data handling. Notably, direct buffers, which are allocated outside of the JVM heap, can provide faster I/O operations, though they come with higher allocation and deallocation costs.

6. Selectors: Streamlining Scalable I/O Operations

Selectors are a unique NIO feature enabling a single thread to monitor multiple channels for readiness, thus efficiently managing numerous I/O operations. This reduces the need for multiple threads, cutting down on resource usage and context switching, which is particularly advantageous in high-performance environments.

7. Improved Performance and Scalability

The amalgamation of channels, buffers, and selectors provides a substantial performance boost. The non-blocking nature of NIO minimizes idle thread time, and managing multiple channels with a single thread significantly improves the scalability. This is pivotal in server environments dealing with numerous simultaneous connections.

Java NIO offers a robust, scalable, and efficient framework for handling I/O operations, addressing many of the limitations of traditional I/O. Its design is particularly advantageous for high-throughput and concurrent-processing systems.

While the complexity of NIO might be higher compared to traditional I/O, the performance and scalability benefits it provides make it an indispensable tool for developers working on large-scale, I/O-intensive Java applications.

43. Explain the Observer Pattern

The Observer pattern is a design pattern where an object, known as the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

It's particularly useful in the scenario where a single object needs to notify an array of objects about a change in its state. In the context of a newsletter system, the Observer pattern can be effectively used to notify subscribers whenever a new post is available.

How to Implement the Observer Pattern for a Newsletter System

Let's break down the implementation using the Observer pattern in the context of a newsletter system:

  • Subject (Newsletter) : This is the entity being observed. It will notify all attached observers when a new post is available.
  • Observer (Subscriber) : These are the observers who wish to be notified about new posts in the newsletter.
  • Client : This will use both the Subject and Observers.

Step 1: Create the Subject Class (Newsletter)

Step 2: create the observer abstract class (subscriber), step 3: create concrete observer classes.

EmailSubscriber.java

SMSSubscriber.java

Step 4: Use the Newsletter and Concrete Subscriber Objects

Step 5: output verification.

When running NewsletterSystemDemo , the output will be something like:

This output indicates that both the email and SMS subscribers are notified whenever the newsletter has a new post.

The Observer pattern provides a clean and straightforward way to implement a subscription mechanism in a newsletter system, ensuring that all subscribers are automatically updated with the latest posts.

This pattern enhances modularity and separation of concerns, making the system easier to understand, maintain, and extend.

44. Explain the Purpose of the this Keyword.

The this keyword in Java serves a very specific and useful purpose. It refers to the current instance of the class in which it is used. This is particularly valuable in scenarios where you need to distinguish between class fields (instance variables) and parameters or variables within a method that have the same name. Let's break it down:

Reference to Instance Variables: When a class’s field is shadowed by a method or constructor parameter, this can be used for referencing the class's field. For instance, in a setter method, this helps differentiate between the instance variable and the parameter passed to the method.

Calling One Constructor from Another: In a class with overloaded constructors, this can be used to call one constructor from another, avoiding code duplication.

Returning the Current Instance: Methods can return this to return the current class instance. This is often used in method chaining.

Passing the Current Instance to Another Method: this can be passed as an argument in the method call or constructor call. This is common in event handling.

Disambiguation: It eliminates ambiguity when instance variables and parameters or local variables share the same name.

image-33

45. Explain Java's try-with-resources.

Java's try-with-resources, introduced in Java 7, is a mechanism that ensures more efficient handling of resources, like files or sockets, in Java. Its primary purpose is to simplify the cleanup of resources which must be closed after their operations are completed.

Key Characteristics:

Automatic Resource Management: In try-with-resources, resources declared within the try clause are automatically closed at the end of the statement, even if exceptions are thrown. This reduces boilerplate code significantly as compared to traditional try-catch-finally blocks.

Syntax: The resources that implement java.lang.AutoCloseable or java.io.Closeable are declared and initialized within parentheses just after the try keyword.

  • Here, the BufferedReader instance is automatically closed when the try block exits, regardless of whether it exits normally or due to an exception.
  • Exception Handling: Any exception thrown by the automatic closure of resources is suppressed if an exception is thrown in the try block. These suppressed exceptions can be retrieved using Throwable.getSuppressed() method.
  • Improved Readability and Reliability: This structure enhances code readability and reliability. It reduces the risk of resource leaks, as the closing of resources is handled automatically.
  • Use in Custom Resources: Custom classes can also utilize this mechanism by implementing the AutoCloseable interface and overriding the close method.

Practical Implications:

In real-world applications, try-with-resources ensures that resources like file streams, database connections, or network sockets are closed properly, preventing resource leaks which could lead to performance issues and other bugs. It is especially valuable in large-scale applications where resource management is critical for efficiency and reliability.

46. Explain the Difference between C++ and Java.

When distinguishing between C++ and Java, it's important to understand that both are powerful programming languages with their unique characteristics and use cases.

They share some similarities, as both are object-oriented and have similar syntax (being influenced by C), but there are key differences that set them apart.

Language Nature and Design Philosophy:

C++ is a multi-paradigm language that supports both procedural and object-oriented programming. It's often chosen for system-level programming due to its efficiency and fine-grained control over memory management.

Java , on the other hand, is primarily object-oriented and designed with a simpler approach to avoid common programming errors (like pointer errors in C++). Java's design principle "Write Once, Run Anywhere" (WORA) emphasizes portability, which is achieved through the Java Virtual Machine (JVM).

Memory Management:

In C++ , memory management is manual. Programmers have direct control over memory allocation and deallocation using operators like new and delete .

Java abstracts away the complexity of direct memory management through its Automatic Garbage Collection, which periodically frees memory that's no longer in use, reducing the likelihood of memory leaks but at the cost of less control and potential overhead.

Platform Dependency and Portability:

C++ is platform-dependent. A C++ program needs to be compiled for each specific platform it's intended to run on, which can lead to more work when targeting multiple platforms.

Java is platform-independent at the source level. Java programs are compiled into bytecode, which can run on any device equipped with a JVM, making it highly portable.

Runtime and Performance:

C++ generally offers higher performance than Java. It compiles directly to machine code, which the CPU executes, resulting in faster execution suitable for performance-critical applications.

Java may have slower performance due to the added abstraction layer of the JVM. But improvements in Just-In-Time (JIT) compilers within the JVM have significantly narrowed this performance gap.

Pointers and Memory Safety:

C++ supports both pointers and references, allowing for powerful, albeit potentially risky, memory manipulation.

Java has references but does not support pointers (at least not in the traditional sense), reducing the risk of memory access errors, thereby increasing program safety.

Exception Handling:

C++ supports exception handling but does not enforce error handling (uncaught exceptions can lead to undefined behavior).

Java has a robust exception handling mechanism, requiring checked exceptions to be caught or declared in the method signature, promoting better error management practices.

Multi-Threading:

C++ has more complex approaches to multi-threading and requires careful management to ensure thread safety.

Java provides built-in support for multi-threading with synchronized methods and blocks, making concurrent programming more manageable.

Standard Template Library (STL) vs. Java Standard Library:

C++ 's STL is a powerful library that offers containers, algorithms, iterators, and so on for efficient data manipulation.

Java 's Standard Library provides a rich set of APIs, including collections, streams, networking, and so on with a focus on ease of use.

Legacy and Use Cases:

C++ is often chosen for system/software development, game development, and applications where hardware access and performance are critical.

Java is widely used in enterprise environments, web services, and Android app development due to its portability and robust libraries.

Both C++ and Java have their strengths and are chosen based on the requirements of the project.

C++ is preferred for scenarios where performance and memory control are crucial, while Java is ideal for applications where portability and ease of use are more important.

Understanding these differences is key in selecting the right language for a particular task or project, and adapting to the strengths of each can lead to more efficient and effective programming practices.

47. What is Polymorphism? Provide an Example.

Polymorphism, a fundamental concept in object-oriented programming, allows objects to be treated as instances of their parent class or interface. It’s a Greek word meaning “many shapes” and in programming, it refers to the ability of a single function or method to work in different ways based on the object it is acting upon.

There are two primary types of polymorphism: compile-time (or static) polymorphism and runtime (or dynamic) polymorphism.

Compile-Time Polymorphism : This is achieved through method overloading and operator overloading. It’s called compile-time polymorphism because the decision about which method to call is made by the compiler.

Method Overloading involves having multiple methods in the same scope, with the same name but different parameters.

In this example, the operate method is overloaded with different parameter types, allowing it to behave differently based on the type of arguments passed.

Runtime Polymorphism : This is mostly achieved through method overriding, which is a feature of inheritance in object-oriented programming. In runtime polymorphism, the method to be executed is determined at runtime.

Method Overriding involves defining a method in a subclass that has the same name, return type, and parameters as a method in its superclass.

In this example, the speak method in the subclass Dog overrides the speak method in its superclass Animal . When the speak method is called on an object of type Dog , the overridden method in the Dog class is executed, demonstrating runtime polymorphism.

Why Polymorphism is Important

  • Flexibility and Extensibility : Polymorphism allows for flexible and extensible code. You can create a more generalized code that works on the superclass type, and it automatically adapts to the specific subclass types.
  • Code Reusability : It enables the reuse of code through inheritance and the ability to override or overload methods.
  • Loose Coupling : By using polymorphic behavior, components can be designed loosely coupled, which means a change in one part of the system causes minimal or no effect on other parts of the system.
  • Simplifies Code Maintenance : With polymorphism, developers can write more maintainable and manageable code, as changes to a superclass are inherited by all subclasses, reducing the need for changes across multiple classes.

Polymorphism is a cornerstone in the world of object-oriented programming, enabling more dynamic and flexible code. It allows objects to interact in a more abstract manner, focusing on the shared behavior rather than the specific types.

Understanding and effectively using polymorphism can lead to more robust and maintainable code, a crucial aspect for any software developer looking to excel in their field.

48. How Can You Avoid Memory Leaks in Java?

Avoiding memory leaks in Java, despite its automated garbage collection mechanism, requires a deep understanding of how memory allocation and release work in Java, alongside meticulous coding practices and effective use of analysis tools.

Let’s delve into some advanced and specific strategies for preventing memory leaks in Java applications:

Understand Object Lifecycle and Scope:

  • Scope Management : Ensure objects are scoped as narrowly as possible. For instance, use local variables within methods rather than class-level variables if the data does not need to persist beyond the method’s execution context.
  • Reference Management : Be cautious with static references. Static fields can keep objects alive for the lifetime of the class, potentially leading to memory leaks.

Efficient Use of Collections:

  • WeakHashMap : For cache implementations, consider using WeakHashMap . It uses weak references for keys, which allows keys (and their associated values) to be garbage-collected when no longer in use.
  • Data Structure Choice : Be mindful of the choice of data structure. For example, use ArrayList over LinkedList for large lists of data where frequent access is required, as LinkedList can consume more memory due to the storage of additional node references.

Leveraging WeakReferences and SoftReferences :

  • SoftReferences for Caches : Use SoftReference for memory-sensitive caches. The garbage collector will only remove soft-referenced objects if it needs memory, making them more persistent than weak references.
  • WeakReferences for Listeners : Utilize WeakReference for listener patterns where listeners might not be explicitly removed.

Managing Resources and I/O:

  • AutoCloseable and Try-with-Resources : For resources like streams, files, and connections, use try-with-resources for automatic closure. Ensure that objects implementing AutoCloseable are closed properly to release resources.

Inner Classes Handling:

  • Static Inner Classes : Prefer static inner classes over non-static to avoid the implicit reference to the outer class instance, which can prevent the outer instance from being garbage-collected.

Profiling and Leak Detection:

  • Heap Dump Analysis : Regularly analyze heap dumps in tools like Eclipse Memory Analyzer (MAT) to detect large objects and potential memory leaks.
  • Java Flight Recorder : Use Java Flight Recorder for runtime analysis and monitoring, which can help identify memory leaks.

ThreadLocal Variables Management:

  • Explicit Removal : Always remove ThreadLocal variables after use, particularly in thread-pooled environments like servlet containers or application servers.

ClassLoader Leaks:

  • ClassLoader Lifecycle : In environments with dynamic class loading/unloading (for example, web servers), ensure that class loaders are garbage collected when not needed. This involves ensuring that classes loaded by these class loaders are no longer referenced.

Garbage Collection Tuning:

  • GC Analysis : Analyze GC logs to understand the garbage collection behavior and identify potential memory leaks.
  • GC Algorithm Choice : Choose an appropriate garbage collection algorithm based on application needs, which can be tuned with JVM options for optimal performance.

String Interning:

  • Selective Interning : Be cautious with the String.intern() method. Unnecessary interning of strings can lead to a bloated String pool.

Static Analysis Tools:

Utilize tools like SonarQube, FindBugs, or PMD to statically analyze code for patterns that could lead to memory leaks.

Developer Training and Code Reviews:

Regularly train developers on best practices in memory management and conduct thorough code reviews with a focus on potential memory leak patterns.

Memory leak prevention in Java is a sophisticated practice that involves a thorough understanding of Java memory management, careful coding, diligent use of analysis tools, and regular monitoring.

By adopting these advanced practices, developers can significantly mitigate the risk of memory leaks, leading to more robust, efficient, and scalable Java applications.

49. Explain the Purpose of Java's Synchronized Block

The purpose of Java's synchronized block is to ensure thread safety in concurrent programming by controlling access to a shared resource among multiple threads.

In a multithreaded environment, where multiple threads operate on the same object, there's a risk of data inconsistency if the threads simultaneously modify the object. A synchronized block in Java is used to lock an object for exclusive access by a single thread.

Thread Safety and Data Consistency:

When different threads access and modify shared data, it can lead to unpredictable data states and inconsistencies. The synchronized block ensures that only one thread can execute a particular block of code at a time, thus maintaining data integrity.

Lock Mechanism:

In Java, each object has an intrinsic lock or monitor lock. When a thread enters a synchronized block, it acquires the lock on the specified object. Other threads attempting to enter the synchronized block on the same object are blocked until the thread inside the synchronized block exits, thereby releasing the lock.

Syntax and Usage:

The synchronized block is defined within a method, and you must specify the object that provides the lock:

The lockObject is a reference to the object whose lock the synchronized block acquires. It can be this to lock the current object, a class object for class-level locks, or any other object.

Advantages Over Synchronized Methods:

Compared to synchronized methods, synchronized blocks provide finer control over the scope and duration of the lock.

While a synchronized method locks the entire method, a synchronized block can lock only the part of the method that needs synchronization, potentially improving performance.

Avoiding Deadlocks:

Take care to avoid deadlocks, a situation where two or more threads are blocked forever, each waiting for the other's lock. This usually occurs when multiple synchronized blocks are locking objects in an inconsistent order.

Synchronized blocks also solve memory visibility problems. Changes made by one thread in a synchronized block are visible to other threads entering subsequent synchronized blocks on the same object.

Best Practices

  • Minimize Lock Contention : Keep the synchronized sections as short as possible to minimize lock contention and avoid performance bottlenecks.
  • Consistent Locking Order : Always acquire locks in a consistent order to prevent deadlocks.
  • Avoid Locking on Public Objects : Locking on public objects can lead to accidental and uncontrolled access to the lock, increasing the deadlock risk. Prefer private objects as lock targets.
  • Complement with Other Concurrency Tools : In some cases, using higher-level concurrency tools like ReentrantLock , Semaphore , or concurrent collections from java.util.concurrent package might be more appropriate.

Java's synchronized block is a critical tool for achieving thread safety in concurrent applications. Its proper use ensures data integrity and consistency by controlling access to shared resources. But, it requires careful consideration to avoid common pitfalls like deadlocks and performance issues due to excessive lock contention.

Understanding and applying these concepts is essential for developers working in a multithreaded environment to create robust and efficient Java applications.

50. Explain the Concept of Modules in Java

Modules in Java, introduced in Java 9 with the Java Platform Module System (JPMS), represent a fundamental shift in organizing Java applications and their dependencies.

Understanding modules is essential for modern Java development, as they offer improved encapsulation, reliable configuration, and scalable system architectures.

What are Java modules?

A module in Java is a self-contained unit of code and data, with well-defined interfaces for communicating with other modules. Each module explicitly declares its dependencies on other modules.

Modules enable better encapsulation by allowing a module to expose only those parts of its API which should be accessible to other modules, while keeping the rest of its codebase hidden. This reduces the risk of unintended usage of internal APIs.

Key Components of modules:

module-info.java : Each module must have a module-info.java file at its root, which declares the module's name, its required dependencies, and the packages it exports.

  • Here, com.example.myapp is the module name, java.sql is a required module, and com.example.myapp.api is the exported package.
  • Exports and Requires: The exports keyword specifies which packages are accessible to other modules, while requires lists the modules on which the current module depends.
  • Improved Application Structure: Modules encourage a cleaner, more organized code structure, helping in maintaining large codebases and improving code quality.
  • Reduced Memory Footprint: By only loading the required modules, applications can reduce their memory footprint and start-up time, enhancing performance.
  • Enhanced Security and Maintenance: Modules reduce the surface area for potential security vulnerabilities. They also simplify dependency management, making it easier to update and maintain libraries without affecting the entire system.

Consider a scenario where you are developing a large-scale application with various functionalities like user management, data processing, and reporting. By organizing these functionalities into separate modules (like usermodule , dataprocessmodule , reportmodule ), you can maintain them independently, avoiding the complexities of a monolithic application structure.

Modules in Java are a powerful feature for building scalable, maintainable, and efficient applications. They offer clear boundaries and contracts between different parts of a system, facilitating better design and architecture.

For developers and teams aiming to build robust Java applications, understanding and leveraging modules is not just a technical skill but a strategic approach to software development.

This modular architecture aligns with modern development practices, enabling Java applications to be more scalable and easier to manage in the long term.

image-34

As we wrap up this roundup of Java interview questions, I want to take a moment to thank the freeCodeCamp team. This platform is a fantastic resource for people learning to code, and it's great to have such a supportive community in the tech world.

I also want to thank the editorial team for their help in making this guide possible. Working together has been a great experience, and it's been rewarding to combine our efforts to help others learn Java.

It's important to reflect on the journey we've undertaken together. Java's robustness in Object-Oriented Programming (OOP) is a critical asset for developers at all levels, especially those aspiring to join top-tier tech firms. This handbook has aimed to provide a clear pathway to mastering Java interviews, focusing on the insights and techniques that matter most in the competitive landscape of big tech.

From the fundamentals to the more complex aspects of Java, I've sought to bridge the gap between basic Java knowledge and the sophisticated expertise that industry leaders like Google value. This resource is crafted not just for those new to Java, but also for those revisiting key concepts, offering a comprehensive understanding of the language in a practical context.

As you continue to explore the depths of Java, remember that mastering this language is not just about enhancing coding skills, but also about expanding your professional horizons. Java's significant role in IoT and its presence in billions of devices worldwide make it a language that can truly shape your career.

In closing, I hope this handbook has provided you with valuable insights and a strong foundation for your future endeavors in Java programming and beyond. Whether you're preparing for a big tech interview or simply looking to refine your software development skills, this guide is a stepping stone towards achieving those goals.

If you're keen on furthering your Java knowledge, here's a guide to help you conquer Java and launch your coding career . It's perfect for those interested in AI and machine learning, focusing on effective use of data structures in coding. This comprehensive program covers essential data structures, algorithms, and includes mentorship and career support.

Additionally, for more practice in data structures, you can explore these resources:

  • Java Data Structures Mastery - Ace the Coding Interview : A free eBook to advance your Java skills, focusing on data structures for enhancing interview and professional skills.
  • Foundations of Java Data Structures - Your Coding Catalyst : Another free eBook, diving into Java essentials, object-oriented programming, and AI applications.

Visit LunarTech's website for these resources and more information on the bootcamp .

Connect with Me:

  • Follow me on LinkedIn for a ton of Free Resources in CS, ML and AI
  • Visit my Personal Website
  • Subscribe to my The Data Science and AI Newsletter

About the Author

I'm Vahe Aslanyan, deeply engaged in the intersecting worlds of computer science, data science, and AI. I invite you to explore my portfolio at vaheaslanyan.com, where I showcase my journey in these fields. My work focuses on blending full-stack development with AI product optimization, all fueled by a passion for innovative problem-solving.

6539302e3cd34bb5cbabe5f9_Vahe%20Aslanyan%20(256%20x%20256%20px)

I've had the privilege of contributing to the launch of a well-regarded data science bootcamp and collaborating with some of the best minds in the industry. My goal has always been to raise the bar in tech education, making it accessible and standard for everyone.

As we conclude our journey here, I want to thank you for your time and engagement. Sharing my professional and academic experiences in this book has been a rewarding experience. I appreciate your involvement and look forward to seeing how it helps you advance in the tech world.

I'm Vahe Aslanyan, dedicated to making AI and data science education inclusive and accessible. I guide developers towards clear tech understanding in software engineering.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

21 Essential Java Interview Questions  *

Toptal sourced essential questions that the best java developers and engineers can answer. driven from our community, we encourage experts to submit questions and offer feedback..

problem solving interview questions for java

Interview Questions

Describe and compare fail-fast and fail-safe iterators. Give examples.

The main distinction between fail-fast and fail-safe iterators is whether or not the collection can be modified while it is being iterated. Fail-safe iterators allow this; fail-fast iterators do not.

Fail-fast iterators operate directly on the collection itself. During iteration, fail-fast iterators fail as soon as they realize that the collection has been modified (i.e., upon realizing that a member has been added, modified, or removed) and will throw a ConcurrentModificationException . Some examples include ArrayList , HashSet , and HashMap (most JDK1.4 collections are implemented to be fail-fast).

Fail-safe iterates operate on a cloned copy of the collection and therefore do not throw an exception if the collection is modified during iteration. Examples would include iterators returned by ConcurrentHashMap or CopyOnWriteArrayList .

ArrayList , LinkedList , and Vector are all implementations of the List interface. Which of them is most efficient for adding and removing elements from the list? Explain your answer, including any other alternatives you may be aware of.

Of the three, LinkedList is generally going to give you the best performance. Here’s why:

ArrayList and Vector each use an array to store the elements of the list. As a result, when an element is inserted into (or removed from) the middle of the list, the elements that follow must all be shifted accordingly. Vector is synchronized, so if a thread-safe implementation is not needed, it is recommended to use ArrayList rather than Vector.

LinkedList , on the other hand, is implemented using a doubly linked list. As a result, an inserting or removing an element only requires updating the links that immediately precede and follow the element being inserted or removed.

However, it is worth noting that if performance is that critical, it’s better to just use an array and manage it yourself, or use one of the high performance 3rd party packages such as Trove or HPPC .

Why would it be more secure to store sensitive data (such as a password, social security number, etc.) in a character array rather than in a String?

In Java, Strings are immutable and are stored in the String pool. What this means is that, once a String is created, it stays in the pool in memory until being garbage collected. Therefore, even after you’re done processing the string value (e.g., the password), it remains available in memory for an indeterminate period of time thereafter (again, until being garbage collected) which you have no real control over. Therefore, anyone having access to a memory dump can potentially extract the sensitive data and exploit it.

In contrast, if you use a mutable object like a character array, for example, to store the value, you can set it to blank once you are done with it with confidence that it will no longer be retained in memory.

Apply to Join Toptal's Development Network

and enjoy reliable, steady, remote Freelance Java Developer Jobs

What is the ThreadLocal class? How and why would you use it?

A single ThreadLocal instance can store different values for each thread independently. Each thread that accesses the get() or set() method of a ThreadLocal instance is accessing its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or transaction ID). The example below, from the ThreadLocal Javadoc , generates unique identifiers local to each thread. A thread’s id is assigned the first time it invokes ThreadId.get() and remains unchanged on subsequent calls.

Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

What is the volatile keyword? How and why would you use it?

In Java, each thread has its own stack, including its own copy of variables it can access. When the thread is created, it copies the value of all accessible variables into its own stack. The volatile keyword basically says to the JVM “Warning, this variable may be modified in another Thread”.

In all versions of Java, the volatile keyword guarantees global ordering on reads and writes to a variable. This implies that every thread accessing a volatile field will read the variable’s current value instead of (potentially) using a cached value.

In Java 5 or later, volatile reads and writes establish a happens-before relationship, much like acquiring and releasing a mutex.

Using volatile may be faster than a lock, but it will not work in some situations. The range of situations in which volatile is effective was expanded in Java 5; in particular, double-checked locking now works correctly.

The volatile keyword is also useful for 64-bit types like long and double since they are written in two operations. Without the volatile keyword you risk stale or invalid values.

One common example for using volatile is for a flag to terminate a thread. If you’ve started a thread, and you want to be able to safely interrupt it from a different thread, you can have the thread periodically check a flag (i.e., to stop it, set the flag to true ). By making the flag volatile, you can ensure that the thread that is checking its value will see that it has been set to true without even having to use a synchronized block. For example:

Compare the sleep() and wait() methods in Java, including when and why you would use one vs. the other.

sleep() is a blocking operation that keeps a hold on the monitor / lock of the shared object for the specified number of milliseconds.

wait() , on the other hand, simply pauses the thread until either (a) the specified number of milliseconds have elapsed or (b) it receives a desired notification from another thread (whichever is first), without keeping a hold on the monitor/lock of the shared object.

sleep() is most commonly used for polling, or to check for certain results, at a regular interval. wait() is generally used in multithreaded applications, in conjunction with notify() / notifyAll() , to achieve synchronization and avoid race conditions.

Tail recursion is functionally equivalent to iteration. Since Java does not yet support tail call optimization, describe how to transform a simple tail recursive function into a loop and why one is typically preferred over the other.

Here is an example of a typical recursive function, computing the arithmetic series 1, 2, 3…N. Notice how the addition is performed after the function call. For each recursive step, we add another frame to the stack.

Tail recursion occurs when the recursive call is in the tail position within its enclosing context - after the function calls itself, it performs no additional work. That is, once the base case is complete, the solution is apparent. For example:

Here you can see that a plays the role of the accumulator - instead of computing the sum on the way down the stack, we compute it on the way up, effectively making the return trip unnecessary, since it stores no additional state and performs no further computation. Once we hit the base case, the work is done - below is that same function, “unrolled”.

Many functional languages natively support tail call optimization, however the JVM does not. In order to implement recursive functions in Java, we need to be aware of this limitation to avoid StackOverflowError s. In Java, iteration is almost universally preferred to recursion.

How can you swap the values of two numeric variables without using any other variables?

You can swap two values a and b without using any other variables as follows:

How can you catch an exception thrown by another thread in Java?

This can be done using Thread.UncaughtExceptionHandler .

Here’s a simple example:

What is the Java Classloader? List and explain the purpose of the three types of class loaders.

The Java Classloader is the part of the Java runtime environment that loads classes on demand (lazy loading) into the JVM (Java Virtual Machine). Classes may be loaded from the local file system, a remote file system, or even the web.

When the JVM is started, three class loaders are used: 1. Bootstrap Classloader: Loads core java API file rt.jar from folder. 2. Extension Classloader: Loads jar files from folder. 3. System/Application Classloader: Loads jar files from path specified in the CLASSPATH environment variable.

Is a finally block executed when an exception is thrown from a try block that does not have a catch block, and if so, when?

A finally block is executed even if an exception is thrown or propagated to the calling code block.

Output can vary, being either:

When designing an abstract class, why should you avoid calling abstract methods inside its constructor?

This is a problem of initialization order. The subclass constructor will not have had a chance to run yet and there is no way to force it to run it before the parent class. Consider the following example class:

This seems like a good start for an abstract Widget: it allows subclasses to fill in width and height , and caches their initial values. However, look when you spec out a typical subclass implementation like so:

Now we’ve introduced a subtle bug: Widget.cachedWidth and Widget.cachedHeight will always be zero for SquareWidget instances! This is because the this.size = size assignment occurs after the Widget constructor runs.

Avoid calling abstract methods in your abstract classes’ constructors, as it restricts how those abstract methods can be implemented.

What variance is imposed on generic type parameters? How much control does Java give you over this?

Java’s generic type parameters are invariant . This means for any distinct types A and B , G<A> is not a subtype or supertype of G<B> . As a real world example, List<String> is not a supertype or subtype of List<Object> . So even though String extends (i.e. is a subtype of) Object , both of the following assignments will fail to compile:

Java does give you some control over this in the form of use-site variance . On individual methods, we can use ? extends Type to create a covariant parameter. Here’s an example:

Even though longs is a List<Long> and not List<Number> , it can be passed to sum .

Similarly, ? super Type lets a method parameter be contravariant . Consider a function with a callback parameter:

forEachNumber allows Callback<Object> to be a subtype of Callback <Number> , which means any callback that handles a supertype of Number will do:

Note, however, that attempting to provide a callback that handles only Long (a subtype of Number ) will rightly fail:

Liberal application of use-site variance can prevent many of the unsafe casts that often appear in Java code and is crucial when designing interfaces used by multiple developers.

What are static initializers and when would you use them?

A static initializer gives you the opportunity to run code during the initial loading of a class and it guarantees that this code will only run once and will finish running before your class can be accessed in any way.

They are useful for performing initialization of complex static objects or to register a type with a static registry, as JDBC drivers do.

Suppose you want to create a static, immutable Map containing some feature flags. Java doesn’t have a good one-liner for initializing maps, so you can use static initializers instead:

Within the same class, you can repeat this pattern of declaring a static field and immediately initializing it, since multiple static initializers are allowed.

If one needs a Set , how do you choose between HashSet vs. TreeSet ?

At first glance, HashSet is superior in almost every way: O(1) add , remove and contains , vs. O(log(N)) for TreeSet .

However, TreeSet is indispensable when you wish to maintain order over the inserted elements or query for a range of elements within the set.

Consider a Set of timestamped Event objects. They could be stored in a HashSet , with equals and hashCode based on that timestamp. This is efficient storage and permits looking up events by a specific timestamp, but how would you get all events that happened on any given day? That would require a O(n) traversal of the HashSet , but it’s only a O(log(n)) operation with TreeSet using the tailSet method:

If Event happens to be a class that we cannot extend or that doesn’t implement Comparable , TreeSet allows us to pass in our own Comparator :

Generally speaking, TreeSet is a good choice when order matters and when reads are balanced against the increased cost of writes.

What are method references, and how are they useful?

Method references were introduced in Java 8 and allow constructors and methods (static or otherwise) to be used as lambdas. They allow one to discard the boilerplate of a lambda when the method reference matches an expected signature.

For example, suppose we have a service that must be stopped by a shutdown hook. Before Java 8, we would have code like this:

With lambdas, this can be cut down considerably:

However, stop matches the signature of Runnable.run ( void return type, no parameters), and so we can introduce a method reference to the stop method of that specific SomeBusyService instance:

This is terse (as opposed to verbose code) and clearly communicates what is going on.

Method references don’t need to be tied to a specific instance, either; one can also use a method reference to an arbitrary object, which is useful in Stream operations. For example, suppose we have a Person class and want just the lowercase names of a collection of people:

A complex lambda can also be pushed into a static or instance method and then used via a method reference instead. This makes the code more reusable and testable than if it were “trapped” in the lambda.

So we can see that method references are mainly used to improve code organization, clarity and terseness.

How are Java enums more powerful than integer constants? How can this capability be used?

Enums are essentially final classes with a fixed number of instances. They can implement interfaces but cannot extend another class.

This flexibility is useful in implementing the strategy pattern, for example, when the number of strategies is fixed. Consider an address book that records multiple methods of contact. We can represent these methods as an enum and attach fields, like the filename of the icon to display in the UI, and any corresponding behaviour, like how to initiate contact via that method:

We can dispense with switch statements entirely by simply using instances of ContactMethod :

This is just the beginning of what can be done with enums. Generally, the safety and flexibility of enums means they should be used in place of integer constants, and switch statements can be eliminated with liberal use of abstract methods.

What does it mean for a collection to be “backed by” another? Give an example of when this property is useful.

If a collection backs another, it means that changes in one are reflected in the other and vice-versa.

For example, suppose we wanted to create a whitelist function that removes invalid keys from a Map . This is made far easier with Map.keySet , which returns a set of keys that is backed by the original map. When we remove keys from the key set, they are also removed from the backing map:

retainAll writes through to the backing map, and allows us to easily implement something that would otherwise require iterating over the entries in the input map, comparing them against allowedKey , etcetera.

Note, it is important to consult the documentation of the backing collection to see which modifications will successfully write through. In the example above, map.keySet().add(value) would fail, because we cannot add a key to the backing map without a value.

What is reflection? Give an example of functionality that can only be implemented using reflection.

Reflection allows programmatic access to information about a Java program’s types. Commonly used information includes: methods and fields available on a class, interfaces implemented by a class, and the runtime-retained annotations on classes, fields and methods.

Examples given are likely to include:

  • Annotation-based serialization libraries often map class fields to JSON keys or XML elements (using annotations). These libraries need reflection to inspect those fields and their annotations and also to access the values during serialization.
  • Model-View-Controller frameworks call controller methods based on routing rules. These frameworks must use reflection to find a method corresponding to an action name, check that its signature conforms to what the framework expects (e.g. takes a Request object, returns a Response ), and finally, invoke the method.
  • Dependency injection frameworks lean heavily on reflection. They use it to instantiate arbitrary beans for injection, check fields for annotations such as @Inject to discover if they require injection of a bean, and also to set those values.
  • Object-relational mappers such as Hibernate use reflection to map database columns to fields or getter/setter pairs of a class, and can go as far as to infer table and column names by reading class and getter names, respectively.

A concrete code example could be something simple, like copying an object’s fields into a map:

Such tricks can be useful for debugging, or for utility methods such as a toString method that works on any class.

Aside from implementing generic libraries, direct use of reflection is rare but it is still a handy tool to have. Knowledge of reflection is also useful for when these mechanisms fail.

However, it is often prudent to avoid reflection unless it is strictly necessary, as it can turn straightforward compiler errors into runtime errors.

Nested classes can be static or non-static (also called an inner class). How do you decide which to use? Does it matter?

The key difference between is that inner classes have full access to the fields and methods of the enclosing class. This can be convenient for event handlers, but comes at a cost: every instance of an inner class retains and requires a reference to its enclosing class.

With this cost in mind, there are many situations where we should prefer static nested classes. When instances of the nested class will outlive instances of the enclosing class, the nested class should be static to prevent memory leaks. Consider this implementation of the factory pattern:

At a glance, this design looks good: the WidgetParserFactory hides the implementation details of the parser with the nested class WidgetParserImpl . However, WidgetParserImpl is not static, and so if WidgetParserFactory is discarded immediately after the WidgetParser is created, the factory will leak, along with all the references it holds.

WidgetParserImpl should be made static, and if it needs access to any of WidgetParserFactory ’s internals, they should be passed into WidgetParserImpl ’s constructor instead. This also makes it easier to extract WidgetParserImpl into a separate class should it outgrow its enclosing class.

Inner classes are also harder to construct via reflection due to their “hidden” reference to the enclosing class, and this reference can get sucked in during reflection-based serialization, which is probably not intended.

So we can see that the decision of whether to make a nested class static is important, and that one should aim to make nested classes static in cases where instances will “escape” the enclosing class or if reflection on those nested classes is involved.

What is the difference between String s = "Test" and String s = new String("Test") ? Which is better and why?

In general, String s = "Test" is more efficient to use than String s = new String("Test") .

In the case of String s = "Test" , a String with the value “Test” will be created in the String pool. If another String with the same value is then created (e.g., String s2 = "Test" ), it will reference this same object in the String pool.

However, if you use String s = new String("Test") , in addition to creating a String with the value “Test” in the String pool, that String object will then be passed to the constructor of the String Object (i.e., new String("Test") ) and will create another String object (not in the String pool) with that value. Each such call will therefore create an additional String object (e.g., String s2 = new String("Test") would create an addition String object, rather than just reusing the same String object from the String pool).

There is more to interviewing than tricky technical questions, so these are intended merely as a guide. Not every “A” candidate worth hiring will be able to answer them all, nor does answering them all guarantee an “A” candidate. At the end of the day, hiring remains an art, a science — and a lot of work .

Tired of interviewing candidates? Not sure what to ask to get you a top hire?

Let Toptal find the best people for you.

Our Exclusive Network of Java Developers

Looking to land a job as a Java Developer?

Let Toptal find the right job for you.

Job Opportunities From Our Network

Submit an interview question

Submitted questions and answers are subject to review and editing, and may or may not be selected for posting, at the sole discretion of Toptal, LLC.

Looking for Java Developers?

Looking for Java Developers ? Check out Toptal’s Java developers.

Julie Wetherbee, Freelance Java Programmer for Hire.

Julie Wetherbee

Julie has over 20 years of experience building software applications and leading engineering teams for businesses of all sizes. She has expertise in Java, JavaScript, C, C++, and Perl, and is familiar with many popular frameworks. Recently, Julie designed and implemented a large-scale Oracle database sharding solution for Walmart.com.

Jean-François Savard, Freelance Java Engineer.

Jean-François Savard

Jean-François is a passionate developer who started coding in Java when he was 14 years old and has rarely passed a day without writing code since then. Notwithstanding his unique experience with Java and its related frameworks, his thirst for knowledge led him to explore several aspects of computer science, such as machine learning, data science, software architecture, and cloud-based development.

Claudio Aldana, Java Engineer.

Claudio Aldana

Claudio is a seasoned IT specialist focused on business outcomes, along with having a solid engineering background. He's applied data science to optimize customer satisfaction, product personalization, and customer churn. Claudio is also a certified SharePoint expert and has worked with prominent Microsoft customers, helping them to maximize security, performance, and usability.

Toptal Connects the Top 3% of Freelance Talent All Over The World.

Join the Toptal community.

Java Interview Questions and Programming Examples

problem solving interview questions for java

This article have been designed to get you prepared with the questions you may encounter during a technical interview for the subject of Java Programming Language. Typical jobs descriptions requiring Java skills are Java Backend programmer and Java Fullstack programmer.

As per my experience, most of the questions are related to:

  • the programming language particularities (syntax, core API)
  • problem solving (algorithms, data structures)
  • application design / architecture (design patterns, object oriented programming, best practices…). 

You'll find below a summary of these question categories and some examples. I hope this will help for your next tech interview!

Java language questions are mainly about classes, methods, objects, syntax and APIs.

Java Books Library

Questions relating to the Java language check the developer’s ability to use functionalities that are well-known. Using the correct APIs and data structures determine the developer's level of experience in the practice of the Java programming language. This skill is particularly important for a developer who has to be quickly operational in a Java working environment. See below a list of the common questions which can be asked by technical recruiters:

  • What is the purpose of the method public static void main in a Java program?
  • What is the difference between System.out.println and System.err.println ?
  • What is an interface in Java?
  • When would you use an abstract class instead of an interface ?
  • What are the differences between a public method and a protected one?
  • What is a static variable?
  • What is an Exception in Java?
  • Is it a good practice to catch a RuntimeException ?
  • What is the keyword to use in a method signature to allow non-catching of an exception in this method?
  • What is the latest version of Java?
  • What is the purpose of a garbage collector?
  • What is the difference between a HashSet and a TreeSet ?
  • Which Thread method is called when a thread starts?
  • Is it possible to update a String object (without using introspection)?
  • What is the contract between the methods equals and hashcode ?
  • Who is James Gosling?

An example of very simple task consists in writing a method which takes a string str as parameter and returns true if it equals to "Hello World" , false otherwise.

Java Problem Solving Questions

Java Algorithms

This skill corresponds to the developer's ability to evaluate and resolve a problem by writing an efficient algorithm in Java. Any developers should be able to solve simple problems but advanced analytical skills and logical reasoning are essential when your are hiring Java R&D developers. Problem Solving exercises cover several topics like the graph theory, dynamic programming and the number theory. Most of the time problem solving questions require to write code or pseudo code directly in a code editor or, sometimes, in front of a white board. See below some questions:

  • What are time and space complexity?
  • What is the O-notation?
  • What is the time complexity of binary search?
  • Given a pointer to the head node of a linked list, reverse this linked list
  • Give the name of 3 sorting algorithms and explain their logic
  • What is the difference between DFS and BFS?
  • Implement a recursive and an iterative method to compute a given Fibonacci number

An example of a simple problem is:

From a given array of natural numbers, return the distance between the two closest numbers.

A basic solution consists in: for each number, compare it to all the other numbers. This solution takes a long time to process large data sets, its time complexity is O(n²) then this implementation can fail on big data sets. A more efficient solution consists in a two steps algorithm:

  • sort the array using a built-in function like Arrays.sort() which has a time complexity of O(n log n).
  • iterate through the sorted array and compare each number to the previous one to find the two closest.

See? This is much better!

Java Design Questions

Application architecture and design

Having a good understanding of the design patterns, OOP (object-oriented programming) and unit tests give an indication of the developer's ability to implement standard solutions to common problems. A developer with a good level of proficiency in this skill will contribute to increase the maintainability and the extensibility of applications. This skill is particularly important for senior Java developers who will have to work on the architecture of applications to design long-term solutions.

This is a simple question example:

A general rule of thumb is to prefer interface over implementation, it improves code maintenance, testability and code portability. Map getTable() is the expected answer.

Java Readability Questions

Code readability

This metric focus on the developer’s ability to follow the Java guidelines and best practices. A high score means that the code is easily understandable by other programmers, easier to maintain and to debug. For example, private String Name; will impact the readability score because it does not respect the Java naming convention: Name should be written name .

Java Reliability Questions

Fixing bugs in practice

Remember str.equals("Hello World") upper? What happens if str is null ? 🧐 This kind of error is like a mine silently waiting in a program.

Reliability refers to the developer's ability to achieve solutions that address specific cases like corner and edge cases. The higher this skill, the higher the developer anticipates possible errors and minimizes those to build robust programs.

About Programming tests

Coding tests are one of the most efficient ways to screen developers before hiring.

The CodinGame Java online tests assess candidates' skills. They are perfect for pre-employment screening for developers. Most of the coding interview tools focus only on the candidates' ability to write efficient algorithms but algorithms are a tiny part of software development, mastering them is one skill among several other important skills. CodinGame Assessment provides tests covering a wide scope of technical characteristics to evaluate candidates' ability to write good Java programs.

They provide a proven model for identifying and hiring proficient developers. Candidates code their way through real, practical problems that they could encounter in a company (such as finding a bug in a defective piece of code or properly synchronizing a multi-threaded application), enabling recruiters to measure their coding skills objectively and efficiently.

Tech recruiters to HR managers can set up coding tests using platforms like CodinGame, choosing to test applicants in one specific programming language or over multiple technologies (Java, Javascript, Python, React etc.).

Candidates’ code is automatically analyzed and recruiters are provided with performance metrics. Once completed, a test report is available to download and share to easily compare and shortlist candidates.

Coding Skills Assessment Tool

The Most Common Java Pitfalls

Beginner java concepts, java behavior driven development, kotlin basics, part 1.

The #1 tech hiring platform

Javatpoint Logo

All Interview

Company interview, technical interview, web interview, php interview, .net interview, java interview, database interview, 3) list the features of java programming language..

There are the following features in Java Programming Language.

  • Simple: Java is easy to learn. The syntax of Java is based on C++ which makes easier to write the program in it.
  • Object-Oriented: Java follows the object-oriented paradigm which allows us to maintain our code as the combination of different type of objects that incorporates both data and behavior.
  • Portable: Java supports read-once-write-anywhere approach. We can execute the Java program on every machine. Java program (.java) is converted to bytecode (.class) which can be easily run on every machine.
  • Platform Independent: Java is a platform independent programming language. It is different from other programming languages like C and C++ which needs a platform to be executed. Java comes with its platform on which its code is executed. Java doesn't depend upon the operating system to be executed.
  • Secured: Java is secured because it doesn't use explicit pointers. Java also provides the concept of ByteCode and Exception handling which makes it more secured.
  • Robust: Java is a strong programming language as it uses strong memory management. The concepts like Automatic garbage collection, Exception handling, etc. make it more robust.
  • Architecture Neutral: Java is architectural neutral as it is not dependent on the architecture. In C, the size of data types may vary according to the architecture (32 bit or 64 bit) which doesn't exist in Java.
  • Interpreted: Java uses the Just-in-time (JIT) interpreter along with the compiler for the program execution.
  • High Performance: Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++).
  • Multithreaded: We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications, etc.
  • Distributed: Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the internet.
  • Dynamic: Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++.

4) What do you understand by Java virtual machine?

Java Virtual Machine is a virtual machine that enables the computer to run the Java program. JVM acts like a run-time engine which calls the main method present in the Java code. JVM is the specification which must be implemented in the computer system. The Java code is compiled by JVM to be a Bytecode which is machine independent and close to the native code.

5) What is the difference between JDK, JRE, and JVM?

JVM is an acronym for Java Virtual Machine; it is an abstract machine which provides the runtime environment in which Java bytecode can be executed. It is a specification which specifies the working of Java Virtual Machine. Its implementation has been provided by Oracle and other companies. Its implementation is known as JRE.

JVMs are available for many hardware and software platforms (so JVM is platform dependent). It is a runtime instance which is created when we run the Java class. There are three notions of the JVM: specification, implementation, and instance.

JRE stands for Java Runtime Environment. It is the implementation of JVM. The Java Runtime Environment is a set of software tools which are used for developing Java applications. It is used to provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.

JDK is an acronym for Java Development Kit. It is a software development environment which is used to develop Java applications and applets. It physically exists. It contains JRE + development tools. JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:

  • Standard Edition Java Platform
  • Enterprise Edition Java Platform
  • Micro Edition Java Platform

6) How many types of memory areas are allocated by JVM?

Many types:

  • Class(Method) Area: Class Area stores per-class structures such as the runtime constant pool, field, method data, and the code for methods.
  • Heap: It is the runtime data area in which the memory is allocated to the objects
  • Stack: Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return. Each thread has a private JVM stack, created at the same time as the thread. A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.
  • Program Counter Register: PC (program counter) register contains the address of the Java virtual machine instruction currently being executed.
  • Native Method Stack: It contains all the native methods used in the application.

7) What is JIT compiler?

Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the bytecode that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

8) What is the platform?

A platform is the hardware or software environment in which a piece of software is executed. There are two types of platforms, software-based and hardware-based. Java provides the software-based platform.

9) What are the main differences between the Java platform and other platforms?

There are the following differences between the Java platform and other platforms.

  • Java is the software-based platform whereas other platforms may be the hardware platforms or software-based platforms.
  • Java is executed on the top of other hardware platforms whereas other platforms can only have the hardware components.

10) What gives Java its 'write once and run anywhere' nature?

The bytecode. Java compiler converts the Java programs into the class file (Byte Code) which is the intermediate language between source code and machine code. This bytecode is not platform specific and can be executed on any computer.

11) What is classloader?

Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded first by the classloader. There are three built-in classloaders in Java.

  • Bootstrap ClassLoader : This is the first classloader which is the superclass of Extension classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, java.net package classes, java.util package classes, java.io package classes, java.sql package classes, etc.
  • Extension ClassLoader : This is the child classloader of Bootstrap and parent classloader of System classloader. It loads the jar files located inside $JAVA_HOME/jre/lib/ext directory.
  • System/Application ClassLoader : This is the child classloader of Extension classloader. It loads the class files from the classpath. By default, the classpath is set to the current directory. You can change the classpath using "-cp" or "-classpath" switch. It is also known as Application classloader.

12) Is Empty .java file name a valid source file name?

Yes, Java allows to save our java file by .java only, we need to compile it by javac .java and run by java classname Let's take a simple example:

compile it by javac .java

run it by java A

13) Is delete, next, main, exit or null keyword in java?

14) if i don't provide any arguments on the command line, then what will the value stored in the string array passed into the main() method, empty or null.

It is empty, but not null.

15) What if I write static public void instead of public static void?

The program compiles and runs correctly because the order of specifiers doesn't matter in Java.

16) What is the default value of the local variables?

The local variables are not initialized to any default value, neither primitives nor object references.

17) What are the various access specifiers in Java?

In Java, access specifiers are the keywords which are used to define the access scope of the method, class, or a variable. In Java, there are four access specifiers given below.

  • Public The classes, methods, or variables which are defined as public, can be accessed by any class or method.
  • Protected Protected can be accessed by the class of the same package, or by the sub-class of this class, or within the same class.
  • Default Default are accessible within the package only. By default, all the classes, methods, and variables are of default scope.
  • Private The private class, methods, or variables defined as private can be accessed within the class only.

18) What is the purpose of static methods and variables?

The methods or variables defined as static are shared among all the objects of the class. The static is the part of the class and not of the object. The static variables are stored in the class area, and we do not need to create the object to access such variables. Therefore, static is used in the case, where we need to define variables or methods which are common to all the objects of the class.

For example, In the class simulating the collection of the students in a college, the name of the college is the common attribute to all the students. Therefore, the college name will be defined as static .

19) What are the advantages of Packages in Java?

There are various advantages of defining packages in Java.

  • Packages avoid the name clashes.
  • The Package provides easier access control.
  • We can also have the hidden classes that are not visible outside and used by the package.
  • It is easier to locate the related classes.

20) What is the output of the following Java program?

The output of the above code will be

Explanation

In the first case, 10 and 20 are treated as numbers and added to be 30. Now, their sum 30 is treated as the string and concatenated with the string Javatpoint . Therefore, the output will be 30Javatpoint .

In the second case, the string Javatpoint is concatenated with 10 to be the string Javatpoint10 which will then be concatenated with 20 to be Javatpoint1020 .

21) What is the output of the following Java program?

In the first case, The numbers 10 and 20 will be multiplied first and then the result 200 is treated as the string and concatenated with the string Javatpoint to produce the output 200Javatpoint .

In the second case, The numbers 10 and 20 will be multiplied first to be 200 because the precedence of the multiplication is higher than addition. The result 200 will be treated as the string and concatenated with the string Javatpoint to produce the output as Javatpoint200 .

22) What is the output of the following Java program?

The above code will give the compile-time error because the for loop demands a boolean value in the second part and we are providing an integer value, i.e., 0.

Core Java - OOPs Concepts: Initial OOPs Interview Questions

There is given more than 50 OOPs (Object-Oriented Programming and System) interview questions. However, they have been categorized in many sections such as constructor interview questions, static interview questions, Inheritance Interview questions, Abstraction interview question, Polymorphism interview questions, etc. for better understanding.

23) What is object-oriented paradigm?

It is a programming paradigm based on objects having data and methods defined in the class to which it belongs. Object-oriented paradigm aims to incorporate the advantages of modularity and reusability. Objects are the instances of classes which interacts with one another to design applications and programs. There are the following features of the object-oriented paradigm.

  • Follows the bottom-up approach in program design.
  • Focus on data with methods to operate upon the object's data
  • Includes the concept like Encapsulation and abstraction which hides the complexities from the user and show only functionality.
  • Implements the real-time approach like inheritance, abstraction, etc.
  • The examples of the object-oriented paradigm are C++, Simula, Smalltalk, Python, C#, etc.

24) What is an object?

The Object is the real-time entity having some state and behavior. In Java, Object is an instance of the class having the instance variables as the state of the object and the methods as the behavior of the object. The object of a class can be created by using the new keyword.

25) What is the difference between an object-oriented programming language and object-based programming language?

There are the following basic differences between the object-oriented language and object-based language.

  • Object-oriented languages follow all the concepts of OOPs whereas, the object-based language doesn't follow all the concepts of OOPs like inheritance and polymorphism.
  • Object-oriented languages do not have the inbuilt objects whereas Object-based languages have the inbuilt objects, for example, JavaScript has window object.
  • Examples of object-oriented programming are Java, C#, Smalltalk, etc. whereas the examples of object-based languages are JavaScript, VBScript, etc.

26) What will be the initial value of an object reference which is defined as an instance variable?

All object references are initialized to null in Java.

Core Java - OOPs Concepts: Constructor Interview Questions

27) what is the constructor.

The constructor can be defined as the special type of method that is used to initialize the state of an object. It is invoked when the class is instantiated, and the memory is allocated for the object. Every time, an object is created using the new keyword, the default constructor of the class is called. The name of the constructor must be similar to the class name. The constructor must not have an explicit return type.

28) How many types of constructors are used in Java?

Based on the parameters passed in the constructors, there are two types of constructors in Java.

  • Default Constructor: default constructor is the one which does not accept any value. The default constructor is mainly used to initialize the instance variable with the default values. It can also be used for performing some useful task on object creation. A default constructor is invoked implicitly by the compiler if there is no constructor defined in the class.
  • Parameterized Constructor: The parameterized constructor is the one which can initialize the instance variables with the given values. In other words, we can say that the constructors which can accept the arguments are called parameterized constructors.

Java Constructors

29) What is the purpose of a default constructor?

The purpose of the default constructor is to assign the default value to the objects. The java compiler creates a default constructor implicitly if there is no constructor in the class.

Explanation: In the above class, you are not creating any constructor, so compiler provides you a default constructor. Here 0 and null values are provided by default constructor.

Java default constructor

30) Does constructor return any value?

Ans: yes, The constructor implicitly returns the current instance of the class (You can't use an explicit return type with the constructor). More Details.

31)Is constructor inherited?

No, The constructor is not inherited.

32) Can you make a constructor final?

No, the constructor can't be final.

33) Can we overload the constructors?

Yes, the constructors can be overloaded by changing the number of arguments accepted by the constructor or by changing the data type of the parameters. Consider the following example.

In the above program, The constructor Test is overloaded with another constructor. In the first call to the constructor, The constructor with one argument is called, and i will be initialized with the value 10. However, In the second call to the constructor, The constructor with the 2 arguments is called, and i will be initialized with the value 15.

34) What do you understand by copy constructor in Java?

There is no copy constructor in java. However, we can copy the values from one object to another like copy constructor in C++.

There are many ways to copy the values of one object into another in java. They are:

  • By constructor
  • By assigning the values of one object into another
  • By clone() method of Object class

In this example, we are going to copy the values of one object into another using java constructor.

35) What are the differences between the constructors and methods?

There are many differences between constructors and methods. They are given below.

Java Constructors vs Methods

36) What is the output of the following Java program?

The output of the following program is:

Here, the data type of the variables a and b, i.e., byte gets promoted to int, and the first parameterized constructor with the two integer parameters is called.

37) What is the output of the following Java program?

The output of the program is 0 because the variable i is initialized to 0 internally. As we know that a default constructor is invoked implicitly if there is no constructor in the class, the variable i is initialized to 0 since there is no constructor in the class.

38) What is the output of the following Java program?

There is a compiler error in the program because there is a call to the default constructor in the main method which is not present in the class. However, there is only one parameterized constructor in the class Test. Therefore, no default constructor is invoked by the constructor implicitly.

Core Java - OOPs Concepts: static keyword Interview Questions

39) what is the static variable.

The static variable is used to refer to the common property of all objects (that is not unique for each object), e.g., The company name of employees, college name of students, etc. Static variable gets memory only once in the class area at the time of class loading. Using a static variable makes your program more memory efficient (it saves memory). Static variable belongs to the class rather than the object.

Static Variable

40) What is the static method?

  • A static method belongs to the class rather than the object.
  • There is no need to create the object to call the static methods.
  • A static method can access and change the value of the static variable.

41) What are the restrictions that are applied to the Java static methods?

Two main restrictions are applied to the static methods.

  • The static method can not use non-static data member or call the non-static method directly.
  • this and super cannot be used in static context as they are non-static.

42) Why is the main method static?

Because the object is not required to call the static method. If we make the main method non-static, JVM will have to create its object first and then call main() method which will lead to the extra memory allocation. More Details.

43) Can we override the static methods?

44) what is the static block.

Static block is used to initialize the static data member. It is executed before the main method, at the time of classloading.

45) Can we execute a program without main() method?

Ans) No, It was possible before JDK 1.7 using the static block. Since JDK 1.7, it is not possible. More Details.

46) What if the static modifier is removed from the signature of the main method?

Program compiles. However, at runtime, It throws an error "NoSuchMethodError."

47) What is the difference between static (class) method and instance method?

48) can we make constructors static.

As we know that the static context (method, block, or variable) belongs to the class, not the object. Since Constructors are invoked only when the object is created, there is no sense to make the constructors static. However, if you try to do so, the compiler will show the compiler error.

49) Can we make the abstract methods static in Java?

In Java, if we make the abstract methods static, It will become the part of the class, and we can directly call it which is unnecessary. Calling an undefined method is completely useless therefore it is not allowed.

50) Can we declare the static variables and methods in an abstract class?

Yes, we can declare static variables and methods in an abstract method. As we know that there is no requirement to make the object to access the static context, therefore, we can access the static context declared inside the abstract class by using the name of the abstract class. Consider the following example.

Core Java - OOPs Concepts: Inheritance Interview Questions

51) what is this keyword in java.

The this keyword is a reference variable that refers to the current object. There are the various uses of this keyword in Java. It can be used to refer to current class properties such as instance methods, variable, constructors, etc. It can also be passed as an argument into the methods or constructors. It can also be returned from the method as the current class instance.

java this keyword

52) What are the main uses of this keyword?

There are the following uses of this keyword.

  • this can be used to refer to the current class instance variable.
  • this can be used to invoke current class method (implicitly)
  • this() can be used to invoke the current class constructor.
  • this can be passed as an argument in the method call.
  • this can be passed as an argument in the constructor call.
  • this can be used to return the current class instance from the method.

53) Can we assign the reference to this variable?

No, this cannot be assigned to any value because it always points to the current class object and this is the final reference in Java. However, if we try to do so, the compiler error will be shown. Consider the following example.

54) Can this keyword be used to refer static members?

Yes, It is possible to use this keyword to refer static members because this is just a reference variable which refers to the current class object. However, as we know that, it is unnecessary to access static variables through objects, therefore, it is not the best practice to use this to refer static members. Consider the following example.

55) How can constructor chaining be done using this keyword?

Constructor chaining enables us to call one constructor from another constructor of the class with respect to the current class object. We can use this keyword to perform constructor chaining within the same class. Consider the following example which illustrates how can we use this keyword to achieve constructor chaining.

56) What are the advantages of passing this into a method instead of the current class object itself?

As we know, that this refers to the current class object, therefore, it must be similar to the current class object. However, there can be two main advantages of passing this into a method instead of the current class object.

  • this is a final variable. Therefore, this cannot be assigned to any new value whereas the current class object might not be final and can be changed.
  • this can be used in the synchronized block.

57) What is the Inheritance?

Inheritance is a mechanism by which one object acquires all the properties and behavior of another object of another class. It is used for Code Reusability and Method Overriding. The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

There are five types of inheritance in Java.

  • Single-level inheritance
  • Multi-level inheritance
  • Multiple Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance

Multiple inheritance is not supported in Java through class.

58) Why is Inheritance used in Java?

There are various advantages of using inheritance in Java that is given below.

  • Inheritance provides code reusability. The derived class does not need to redefine the method of base class unless it needs to provide the specific implementation of the method.
  • Runtime polymorphism cannot be achieved without using inheritance.
  • We can simulate the inheritance of classes with the real-time objects which makes OOPs more realistic.
  • Inheritance provides data hiding. The base class can hide some data from the derived class by making it private.
  • Method overriding cannot be achieved without inheritance. By method overriding, we can give a specific implementation of some basic method contained by the base class.

59) Which class is the superclass for all the classes?

The object class is the superclass of all other classes in Java.

60) Why is multiple inheritance not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class.

Since the compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have the same method or different, there will be a compile time error.

61) What is aggregation?

Aggregation can be defined as the relationship between two classes where the aggregate class contains a reference to the class it owns. Aggregation is best described as a has-a relationship. For example, The aggregate class Employee having various fields such as age, name, and salary also contains an object of Address class having various fields such as Address-Line 1, City, State, and pin-code. In other words, we can say that Employee (class) has an object of Address class. Consider the following example.

Address.java

Employee.java

62) What is composition?

Holding the reference of a class within some other class is known as composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition. In other words, we can say that composition is the particular case of aggregation which represents a stronger relationship between two objects. Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.

63) What is the difference between aggregation and composition?

Aggregation represents the weak relationship whereas composition represents the strong relationship. For example, the bike has an indicator (aggregation), but the bike has an engine (composition).

64) Why does Java not support pointers?

The pointer is a variable that refers to the memory address. They are not used in Java because they are unsafe(unsecured) and complex to understand.

65) What is super in java?

The super keyword in Java is a reference variable that is used to refer to the immediate parent class object. Whenever you create the instance of the subclass, an instance of the parent class is created implicitly which is referred by super reference variable. The super() is called in the class constructor implicitly by the compiler if there is no super or this.

66) How can constructor chaining be done by using the super keyword?

67) what are the main uses of the super keyword.

There are the following uses of super keyword.

  • super can be used to refer to the immediate parent class instance variable.
  • super can be used to invoke the immediate parent class method.
  • super() can be used to invoke immediate parent class constructor.

68) What are the differences between this and super keyword?

There are the following differences between this and super keyword.

  • The super keyword always points to the parent class contexts whereas this keyword always points to the current class context.
  • The super keyword is primarily used for initializing the base class variables within the derived class constructor whereas this keyword primarily used to differentiate between local and instance variables when passed in the class constructor.
  • The super and this must be the first statement inside constructor otherwise the compiler will throw an error.

69) What is the output of the following Java program?

The super() is implicitly invoked by the compiler if no super() or this() is included explicitly within the derived class constructor. Therefore, in this case, The Person class constructor is called first and then the Employee class constructor is called.

70) Can you use this() and super() both in a constructor?

No, because this() and super() must be the first statement in the class constructor.

71)What is object cloning?

The object cloning is used to create the exact copy of an object. The clone() method of the Object class is used to clone an object. The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.

Core Java - OOPs Concepts: Method Overloading Interview Questions

72) what is method overloading.

Method overloading is the polymorphism technique which allows us to create multiple methods with the same name but different signature. We can achieve method overloading in two ways.

  • By Changing the number of arguments
  • By Changing the data type of arguments

Method overloading increases the readability of the program. Method overloading is performed to figure out the program quickly.

73) Why is method overloading not possible by changing the return type in java?

In Java, method overloading is not possible by changing the return type of the program due to avoid the ambiguity.

74) Can we overload the methods by making them static?

No, We cannot overload the methods by just applying the static keyword to them(number of parameters and types are the same). Consider the following example.

75) Can we overload the main() method?

Yes, we can have any number of main methods in a Java program by using method overloading.

76) What is method overloading with type promotion?

By Type promotion is method overloading, we mean that one data type can be promoted to another implicitly if no exact matching is found.

Java Method Overloading with Type Promotion

As displayed in the above diagram, the byte can be promoted to short, int, long, float or double. The short datatype can be promoted to int, long, float or double. The char datatype can be promoted to int, long, float or double and so on. Consider the following example.

77) What is the output of the following Java program?

There are two methods defined with the same name, i.e., sum. The first method accepts the integer and long type whereas the second method accepts long and the integer type. The parameter passed that are a = 20, b = 20. We can not tell that which method will be called as there is no clear differentiation mentioned between integer literal and long literal. This is the case of ambiguity. Therefore, the compiler will throw an error.

Core Java - OOPs Concepts: Method Overriding Interview Questions

78) what is method overriding:.

If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding. It is used for runtime polymorphism and to implement the interface methods.

Rules for Method overriding

  • The method must have the same name as in the parent class.
  • The method must have the same signature as in the parent class.
  • Two classes must have an IS-A relationship between them.

79) Can we override the static method?

No, you can't override the static method because they are the part of the class, not the object.

80) Why can we not override static method?

It is because the static method is the part of the class, and it is bound with class whereas instance method is bound with the object, and static gets memory in class area, and instance gets memory in a heap.

81) Can we override the overloaded method?

82) difference between method overloading and overriding., 83) can we override the private methods.

No, we cannot override the private methods because the scope of private methods is limited to the class and we cannot access them outside of the class.

84) Can we change the scope of the overridden method in the subclass?

Yes, we can change the scope of the overridden method in the subclass. However, we must notice that we cannot decrease the accessibility of the method. The following point must be taken care of while changing the accessibility of the method.

  • The private can be changed to protected, public, or default.
  • The protected can be changed to public or default.
  • The default can be changed to public.
  • The public will always remain public.

85) Can we modify the throws clause of the superclass method while overriding it in the subclass?

Yes, we can modify the throws clause of the superclass method while overriding it in the subclass. However, there are some rules which are to be followed while overriding in case of exception handling.

  • If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception, but it can declare the unchecked exception.
  • If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.

86) What is the output of the following Java program?

87) can you have virtual functions in java.

Yes, all functions in Java are virtual by default.

88) What is covariant return type?

Now, since java5, it is possible to override any method by changing the return type if the return type of the subclass overriding method is subclass type. It is known as covariant return type. The covariant return type specifies that the return type may vary in the same direction as the subclass.

89) What is the output of the following Java program?

The method of Base class, i.e., baseMethod() is overridden in Derived class. In Test class, the reference variable b (of type Base class) refers to the instance of the Derived class. Here, Runtime polymorphism is achieved between class Base and Derived. At compile time, the presence of method baseMethod checked in Base class, If it presence then the program compiled otherwise the compiler error will be shown. In this case, baseMethod is present in Base class; therefore, it is compiled successfully. However, at runtime, It checks whether the baseMethod has been overridden by Derived class, if so then the Derived class method is called otherwise Base class method is called. In this case, the Derived class overrides the baseMethod; therefore, the Derived class method is called.

Core Java - OOPs Concepts: final keyword Interview Questions

90) what is the final variable.

In Java, the final variable is used to restrict the user from updating it. If we initialize the final variable, we can't change its value. In other words, we can say that the final variable once assigned to a value, can never be changed after that. The final variable which is not assigned to any value can only be assigned through the class constructor.

final keyword in java

91) What is the final method?

If we change any method to a final method, we can't override it. More Details.

92) What is the final class?

If we make any class final, we can't inherit it into any of the subclasses.

93) What is the final blank variable?

A final variable, not initialized at the time of declaration, is known as the final blank variable. We can't initialize the final blank variable directly. Instead, we have to initialize it by using the class constructor. It is useful in the case when the user has some data which must not be changed by others, for example, PAN Number. Consider the following example:

94) Can we initialize the final blank variable?

Yes, if it is not static, we can initialize it in the constructor. If it is static blank final variable, it can be initialized only in the static block. More Details.

95) Can you declare the main method as final?

Yes, We can declare the main method as public static final void main(String[] args){}.

96) What is the output of the following Java program?

Since i is the blank final variable. It can be initialized only once. We have initialized it to 20. Therefore, 20 will be printed.

97) What is the output of the following Java program?

The getDetails() method is final; therefore it can not be overridden in the subclass.

98) Can we declare a constructor as final?

The constructor can never be declared as final because it is never inherited. Constructors are not ordinary methods; therefore, there is no sense to declare constructors as final. However, if you try to do so, The compiler will throw an error.

99) Can we declare an interface as final?

No, we cannot declare an interface as final because the interface must be implemented by some class to provide its definition. Therefore, there is no sense to make an interface final. However, if you try to do so, the compiler will show an error.

100) What is the difference between the final method and abstract method?

The main difference between the final method and abstract method is that the abstract method cannot be final as we need to override them in the subclass to give its definition.

You may also like:

  • Java Interview Questions
  • SQL Interview Questions
  • Python Interview Questions
  • JavaScript Interview Questions
  • Angular Interview Questions
  • Selenium Interview Questions
  • Spring Boot Interview Questions
  • HR Interview Questions
  • C Programming Interview Questions
  • C++ Interview Questions
  • Data Structure Interview Questions
  • DBMS Interview Questions
  • HTML Interview Questions
  • IAS Interview Questions
  • Manual Testing Interview Questions
  • OOPs Interview Questions
  • .Net Interview Questions
  • C# Interview Questions
  • ReactJS Interview Questions
  • Networking Interview Questions
  • PHP Interview Questions
  • CSS Interview Questions
  • Node.js Interview Questions
  • Spring Interview Questions
  • Hibernate Interview Questions
  • AWS Interview Questions
  • Accounting Interview Questions

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence Tutorial

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking Tutorial

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering Tutorial

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

Top 20 Java coding interview questions for 2024

problem solving interview questions for java

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

Coding interviews are aimed at gauging how well-prepared a candidate is in terms of language proficiency, foundational knowledge, problem-solving skills, and soft skills. For a position that explicitly mentions a language, such as a job listing for a Java developer, it makes even more sense to spend some time and energy polishing Java skills by exploring the common interview questions asked in such interviews. Doing this not only allows us to benefit directly from the experience of others but more importantly, it’s an opportunity to learn things that we are not aware are gaps in our knowledge.

Java interview questions

In this blog, we cover 20 Java language-specific interview questions on a variety of topics. We’re also including answers to these questions to help you prepare for them. For more interview questions, check out the links at the end of this blog.

problem solving interview questions for java

Learn in-demand tech skills in half the time

Mock Interview

Skill Paths

Assessments

Learn to Code

Tech Interview Prep

Generative AI

Data Science

Machine Learning

GitHub Students Scholarship

Early Access Courses

For Individuals

Try for Free

Gift a Subscription

Become an Author

Become an Affiliate

Earn Referral Credits

Cheatsheets

Frequently Asked Questions

Privacy Policy

Cookie Policy

Terms of Service

Business Terms of Service

Data Processing Agreement

Copyright © 2024 Educative, Inc. All rights reserved.

Arc Talent Career Blog

50+ Important Java Interview Questions and Answers to Know

how to answer Java Interview Questions

Study these essential Java interview questions and answers to prepare for upcoming technical interviews and land the Java job you want.

Need to interview a Java developer for a freelance project or job? Here are 37 essential Java interview questions and answers provided by some of our top Java experts here at Arc.

Although technical interviews can’t gauge how well a candidate would perform on a real-life project, this is still an integral part of the hiring process. Here are some Java interview questions that you can ask a developer to evaluate their understanding of the language.

Basic Java Interview Questions

Intermediate java interview questions.

  • Advanced Java Interview Questions

Looking to hire the best remote developers? Explore  HireAI to see how you can:

⚡️ Get instant candidate matches without searching ⚡️ Identify top applicants from our network of 300,000+ devs with no manual screening ⚡️ Hire 4x faster with vetted candidates (qualified and interview-ready)

Try HireAI and hire top developers now →

1. What’s the difference between  String ,  StringBuffer , and StringBuilder ?

String  is an immutable class. In older JDKs the recommendation when programmatically building a String was to use  StringBuffer  since this was optimized to concatenate multiple Strings together.

However, the methods  StringBuffer  were marked as synchronized, which meant that there was a performance penalty, hence  StringBuilder  was introduced to provide a non-synchronized way to efficiently concatenate and modify  Strings .

2. How do you run a Java application on the command line and set the  classpath  with multiple jars?

This is one of those Java interview questions where some people will be thinking what!? But, I’ve met a lot of Java developers who’ve not run a Java application outside of an IDE for years.

3. What is the difference between  final ,  finalize  and  finally ?

final  is a Java keyword used to indicate that either a method can not override in a subclass, or a class can not be extended or a field can not be modified.  finalize  is a method that gets called on an instance of an Object when it is garbage collected.  finally  is a Java keyword used in exception handling to indicate a block of code that should always be run whether an exception is thrown or not.

4. How does Garbage Collection prevent a Java application from going out of memory?

This is a tricky Java interview question… it doesn’t have to be!

Garbage Collection simply cleans up unused memory when an object goes out of scope and is no longer needed. However, an application could create a huge number of large objects that causes an OutOfMemoryError.

5. What’s the difference between a  ClassNotFoundException  and  NoClassDefFoundError ?

A ClassNotFoundException means the class file for a requested class is not on the classpath of the application. A NoClassDefFoundErrormeans that the class file existed at runtime, but for some reason the class could not be turned into a Class definition.

A common cause is an exception being thrown in static initialization blocks.

Check out our entire set of software development interview questions to help you hire the best developers you possibly can.

  • JavaScript Interview Questions
  • Machine Learning Interview Questions
  • MongoDB Interview Questions
  • TypeScript Interview Questions
  • Selenium Interview Questions
  • Spring Interview Questions
  • Data Engineer Interview Questions
  • React Interview Questions
  • Data Analyst Interview Questions
  • Vue Interview Questions
  • SQL Interview Questions
  • DevOps Interview Questions
  • Engineering Manager Interview Questions
  • Java Interview Questions
  • PHP Interview Questions
  • Ruby on Rails Interview Questions
  • Angular Interview Questions
  • Android Interview Questions
  • Data Warehouse Interview Questions

If you’re a developer, familiarize yourself with the non-technical interview questions commonly asked in the first round by HR recruiters and the questions to ask your interviewer !

Arc is the radically different remote job search platform for developers where companies apply to you. We’ll feature you to great global startups and tech companies hiring remotely so you can land a great remote job in 14 days. We make it easier than ever for software developers and engineers to find great remote jobs. Sign up today and get started .

6. Why isn’t  String ‘s .length() accurate?

It isn’t accurate because it will only account for the number of characters within the String. In other words, it will fail to account for code points outside of what is called the BMP (Basic Multilingual Plane), that is, code points with a value of  U+10000  or greater.

The reason is historical: when Java was first defined, one of its goal was to treat all text as Unicode; but at this time, Unicode did not define code points outside of the BMP. By the time Unicode defined such code points, it was too late for char to be changed.

This means that code points outside the BMP are represented with two chars in Java, in what is called a  surrogate pair . Technically, a char in Java is a UTF-16 code unit.

The correct way to count the real numbers of characters within a String, i.e. the number of code points, is either:

or, with Java 8:

7. Given two double values  d1 ,  d2 , why isn’t it reliable to test their equality using:

Because of  Double.NaN  (literally: “Not a Number”).

will print  false .

The most accurate way to tell whether two double values are equal to one another is to use  Double.compare()  and test against 0, as in:

8. What is the problem with this code:

There are, in fact, two problems:

  • the code relies on the default Charset of the JVM;
  • it supposes that this default Charset can handle all characters.

While the second problem is rarely a concern, the first certainly is a concern.

For instance, in most Windows installations, the default charset is  CP1252 ; but on Linux installations, the default charset will be UTF-8.

As such, such a simple string as “é” will give a different result for this operation depending on whether this code is run on Windows or Linux.

The solution is to always specify a Charset, as in, for instance:

The what is the problem with this code? question is one of the most popular Java interview questions, but it’s not necessarily going to be this one above, of course. Be prepared to do some detective work to identify the issue.

Also, keep in mind: while the problem may be exception handling, method overloading, an access specifier issue, or something else, it could also be nothing at all! This is one of those trick Java interview questions where the answer will rely on your gut that everything is perfect with the code already.

9. What is the JIT?

The JIT is the JVM’s mechanism by which it can optimize code at runtime.

JIT means Just In Time. It is a central feature of any JVM. Among other optimizations, it can perform code inlining, lock coarsening or lock eliding, escape analysis etc.

The main benefit of the JIT is on the programmer’s side: code should be written so that it just works; if the code can be optimized at runtime, more often than not, the JIT will find a way.

(On a more advanced note: the JIT is such a complex piece of machinery that it makes it complicated to do accurate performance benchmarks for JVM code; this is why such frameworks as JMH exist.)

10. How do you make this code print  0.5  instead of  0 ?

prints  0 . Why? How do you make this code print  0.5  instead?

The problem here is that this expression:

has integer literals on both sides of the operator:  1  and  2 . As a consequence, an integer division will be performed, and the result of  1  divided by  2  in an integer division is  0 .

In order for the result to be a double as expected, at least one operand of the operation needs to be a double. For instance:

11. What is the inferred type of the method reference System.out::println?

In this code:

what is the inferred type of the method reference  System.out::println?

It is an  IntConsumer .

IntStream.range(0, 10)  returns an  IntStream , and  IntStream  defines a .forEach() method accepting an IntConsumer as an argument, whose prototype is:

System.out  is a  PrintStream , and a  PrintStream  has a method named  println  which takes an int as an argument and returns void. This matches the signature of an  IntConsumer , hence the result.

12. What is the problem with this code?

The problem is that the Stream returned by  Files.lines()  is not closed.

This should be used instead:

Stream  extends  BaseStream , and  BaseStream  extends  AutoCloseable . While this has no influence on streams you obtain from collections for instance, the stream returned by  Files.lines()  is I/O bound. Neglecting to close it correctly may lead to a resource leak if an error occurs while processing the stream.

13. What will be the contents of a list after a given operation and why?

Consider the following piece of code: (Question provided by Francis Galiegue)

What will be the contents of the list after this operation and why?

The contents will be:

The reason is that there are two removal operations on a List:

  • remove(int index)
  • remove(Object obj)

The JVM will always select the most specific overload of a method; and here we pass an int as an argument, the code therefore removes the element at index 2.

To remove the _element_ 2 from the list, the following needs to be written:

14. Write a function to detect if two strings are anagrams (for example, SAVE and VASE)

This is my go-to first interview question. It helps me gauge a candidate’s ability to understand a problem and write an algorithm to solve it.

If someone has not solved the problem before, I expect to see some code with loops and if/then’s. Maybe some  HashMaps . I look for the ability to break down the problem to see what you need to check, what the edge cases are, and whether the code meets those criteria.

The naive solution is often to loop through the letters of the first string and see if they’re all in the second string. The next thing to look for is that the candidate should also do that in reverse too (check string 1 for string 2’s letters)? The next thing to look for is, what about strings with duplicate letters, like VASES?

If you can realize that these are all required and create a functional, non-ridiculous solution, I am happy.

Of course, one can solve it trivially by sorting and comparing both strings. If someone catches this right away, they usually have seen the problem before. But that’s a good sign that someone cares enough to do prep work. Then we can tackle a harder problem.

The details of the implementation are not important; what’s important is that the candidate understands what they need to do, and also understands why their solution works or doesn’t work. If the candidate can demonstrate this, they’re on the right track.

Here is one way to implement a better solution, comparing sorted strings:

15. What is the contract between equals and hashCode of an object?

The only obligation is that for any objects  o1  and  o2  then if  o1.equals(o2)  is  true  then  o1.hashCode() == o2.hashCode()  is true.

Note that this relationship goes only one way: for any o1, o2 of some class C, where none of o1 and o2 are null, then it can happen that o1.hashCode() == o2.hashCode() is true BUT o1.equals(o2) is false.

16. Can an  enum  be extended?

No. Enum types are final by design.

17. How threadsafe is  enum  in Java?

Creation of an  enum  is guaranteed to be threadsafe. However, the methods on an  enum  type are not necessarily threadsafe

18. How does the JVM handle storing local variables vs storing objects?

Objects are stored on the heap. Variables are a reference to the object.

Local variables are stored on the stack.

19. Identify the problem in the below Java code:

A classic example of escaping references.

When an object of  Bar  is created, the super constructor in  Foo  gets called first, which in turn calls the ‘overridden’  doSomething  method.

The  doSomething  method passes the this instance to the class  Zoom .  Zoom  now can use the ‘ this ‘ instance before it is created entirely. BAD!!!

20. When do you use volatile variables?

When a member variable is accessed by multiple threads and want the value of a volatile field to be visible to all readers (other threads in particular) after a write operation completes on it.

More Important Basic Questions for Java Developers

Keep in mind that, although Java is already an object-oriented programming language, you may want to ask questions about object-oriented programming that are more theoretical, conceptual, and outside general Java programming.

Consider including the following additional core Java interview questions on OOP:

  • What are classes / objects / abstractions / inheritances in object-oriented programming?
  • Can you name the 5 SOLID object-oriented programming design principles?
  • How do method overloading and method overriding work in OOP or Java?
  • What is an abstract class in Java?

problem solving interview questions for java

21. Why do you need to use synchronized methods or blocks?

If threads are being used and a number of threads have to go through a synchronized section of code, only one of them may be executed at a time. This is used to make sure shared variables are not updated by multiple threads.

22. What is the difference between HashMap and ConcurrentHashMap ?

ConcurrentHashMap  is thread-safe; that is the code can be accessed by single thread at a time while  HashMap  is not thread-safe.  ConcurrentHashMap  does not allow NULL keys while  HashMap  allows it.

23. When do you need to override the equals and  hashCode  methods in Java?

By defining  equals()  and  hashCode()  consistently, the candidate can improve the usability of classes as keys in hash-based collections such as  HashMap .

24. What is a Service?

A service is a function that is well-defined, self-contained, and does not depend on the context or state of other services.

25. What is a good use case of calling System.gc() ?

One may call  System.gc()  when profiling an application to search for possible memory leaks. All the profilers call this method just before taking a memory snapshot.

26. What is the marker interface in Java?

The marker interface in Java is an interface with no field or methods. In other words, it an empty interface in java is called a marker interface. An example of a marker interface is a Serializable, Clonable, and Remote interface. These are used to indicate something to the compiler or JVM.

27. How are Annotations better than Marker Interfaces?

Annotations allow one to achieve the same purpose of conveying metadata about the class to its consumers without creating a separate type for it. Annotations are more powerful, too, letting programmers pass more sophisticated information to classes that “consume” it.

28. What are checked and unchecked exceptions? When do you use them?

A  checked  exception is an exception that must be catch, they are checked by the compiler. An  unchecked  exception is mostly runtime exception, and is not required to be catch. In general, use checked exception when the situation is recoverable (retry, display reasonable error message).

29.  int a = 1L; won’t compile and int b = 0; b += 1L;  compiles fine. Why?

When  +=  is used, that’s a compound statement and the compiler internally casts it. Whereas in the first case, the compiler straightaway shouts at you since it is a direct statement.

Compiler behavior and statement types can be confusing, so questions like this will test a candidate’s grasp of these concepts.

30. Why aren’t you allowed to extend more than one class in Java but are allowed to implement multiple interfaces?

Extending classes may cause ambiguity problems. On the other hand, in terms of interfaces, the single method implementation in one class can serve more than one interface.

Other Intermediate Interview Questions for Java Developers

Be sure you ask about multithreading, as it’s one of Java’s most important features. Here are a few Java multithreading questions you want to ask:

  • How does multithreading work?
  • How to implement a thread in Java?
  • How to create daemon threads?
  • What is thread starvation?
  • What is the ExecutorService interface and how does it work?

You can also explore HireAI to skip the line and:

⚡️ Get instant candidate matches without searching ⚡️ Identify top applicants from our network of 250,000+ devs with no manual screening ⚡️ Hire 4x faster with vetted candidates (qualified and interview-ready)

Advanced Java Interview Questions for Experienced Developers

31. why doesn’t the following code generate a  nullpointerexception  even when the instance is  null .

There is no need for an instance while invoking a static member or method since static members belong to a class rather than an instance.

A null reference may be used to access a class (static) variable without causing an exception.

32. Look at the below code. Why is the code printing  true  in the second and  false  in the first case?

JVM’s cache behavior can be confusing, so this question tests that concept. The second output is  true  as we are comparing the references because the JVM tries to save memory when the Integer falls within a range (from -128 to 127).

At point 2, no new reference of type Integer is created for ‘d’. Instead of creating a new object for the Integer type reference variable ‘d’, it is only assigned with a previously created object referenced by ‘c’. All of these are done by JVM.

33. How do you check if the given two strings below are anagrams or not?

34. how do you reverse  string("java programming")  without using iteration and recursion, 35. give real-world examples of when to use an  arraylist  and when to use  linkedlist ..

ArrayList  is preferred when there are more  get(int) , or when search operations need to be performed as every search operation runtime is  O(1) .

If an application requires more  insert(int)  and  delete(int)  operations, then  LinkedList  is preferred, as  LinkedList  does not need to maintain back and forth to preserve continued indices as  arraylist  does. Overall this question tests the proper usage of collections.

36. What is the difference between an Iterator and a ListIterator ?

This question tests the proper usage of collection iterators. One can only use  ListIterator  to traverse  Lists , and cannot traverse a  Set  using  ListIterator .

What’s more, one can only traverse in a forward direction using  Iterator s. Using  ListIterator , one can traverse a  List  in both the directions (forward and backward).

One cannot obtain indexes while using  Iterator . Indexes can be obtained at any point of time while traversing a list using  ListIterator . The methods  nextIndex()  and  previousIndex()  are used for this purpose.

37. What is the advantage of a generic collection?

They enable stronger type checks at compile time.

A Java compiler applies strong type checking to generic code, and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.

Hopefully, you’ve found these interview questions useful when vetting Java developers.

Keep in mind that the technical interview is just one portion of the hiring process. Whether you’re hiring freelance or full-time Java developers, you also want to evaluate their soft skills like communication, problem-solving, time management, and more.

' src=

The Arc team publishes insightful articles and thought leadership pieces related to software engineering careers and remote work. From helping entry-level developers land their first junior role to assisting remote workers struggling with working from home to guiding mid-level programmers as they seek a leadership position, Arc covers it all and more!

Further reading

how to answer Spring Interview Questions

20 Spring Interview Questions and Answers to Know (With MVC & Boot)

software developer or software engineering questions to ask tech recruiters

8 Questions to Ask Recruiters Before Committing to the Dev Hiring Process

how to answer Angular Interview Questions for AngularJS

29 Angular Interview Questions and Answers to Practice & Prepare For

mongodb interview questions and answers

21 MongoDB Interview Questions and Answers to Prep For (Beg. to Adv.)

how to answer DevOps Interview Questions

15+ Top DevOps Interview Questions and Answers to Know

how to answer machine learning interview questions for ML interviews

20 Machine Learning Interview Questions & Answers to Use

{{ activeMenu.name }}

  • Python Courses
  • JavaScript Courses
  • Artificial Intelligence Courses
  • Data Science Courses
  • React Courses
  • Ethical Hacking Courses
  • View All Courses

Fresh Articles

TripleTen Data Science Bootcamp: Insider Review

  • Python Projects
  • JavaScript Projects
  • Java Projects
  • HTML Projects
  • C++ Projects
  • PHP Projects
  • View All Projects

How to Build an HTML Recipe Page (with CSS Formatting)

  • Python Certifications
  • JavaScript Certifications
  • Linux Certifications
  • Data Science Certifications
  • Data Analytics Certifications
  • Cybersecurity Certifications
  • View All Certifications

The 15 Best Project Management Certifications in 2024

  • IDEs & Editors
  • Web Development
  • Frameworks & Libraries
  • View All Programming
  • View All Development
  • App Development
  • Game Development
  • Courses, Books, & Certifications
  • Data Science
  • Data Analytics
  • Artificial Intelligence (AI)
  • Machine Learning (ML)
  • View All Data, Analysis, & AI

Google Career Certificates to Help You Land a Job in 2024

  • Networking & Security
  • Cloud, DevOps, & Systems
  • Recommendations
  • Crypto, Web3, & Blockchain
  • User-Submitted Tutorials
  • View All Blog Content
  • JavaScript Online Compiler
  • HTML & CSS Online Compiler
  • Certifications
  • Programming
  • Development
  • Data, Analysis, & AI
  • Online JavaScript Compiler
  • Online HTML Compiler

Don't have an account? Sign up

Forgot your password?

Already have an account? Login

Have you read our submission guidelines?

Go back to Sign In

problem solving interview questions for java

Top 80 Java Interview Questions and Answers [2024]

To land the job, it helps to review common and challenging Java interview questions. After all, the class-based, general-purpose, object-oriented programming language is one of the most widely used programming languages in the world .

We prepared these Java interview questions with answers from experts. Expect to cover the basics with beginner-friendly topics and much more advanced challenges with specific code to help professional Software Developers and Android Applications Developers. 

Remember that, with a plethora of great features , the programming language is preferred not only by seasoned experts but also by those new to the programming world. Our interview questions start with basic Java concepts and progress to much more difficult challenges.

Whether you're seeking a new gig or hiring to expand your team, read on to review the best Java interview questions for 2024.

  • Top Java Interview Questions and Answers

We also recommend you brush up on your Java skills with this Java Cheat Sheet before starting your Java interview preparation. 

We have divided these interview questions into several sections. Check the breakdown below to review basic, advanced, OOPs, exception handling, and programming Java interview questions. We also have specific examples of code. Review the coding Java interview questions section for reference.

Basic Java Interview Questions

1. what is java.

Java is an object-oriented, high-level, general-purpose programming language originally designed by James Gosling and further developed by the Oracle Corporation. It is one of the most popular programming languages in the world . 

2. What is the Java Virtual Machine? 

Java Virtual Machine

JVM is a program that interprets the intermediate Java byte code and generates the desired output. It is because of bytecode and JVM that programs written in Java are highly portable. 

3. What are the features of Java?

The following are the various features of the Java programming language:

  • High Performance: Using a JIT (Just-In-Time) compiler allows high performance in Java. The JIT compiler converts the Java bytecode into machine language code, which then gets executed by the JVM.
  • Multi-threading: A thread is a flow of execution. The JVM creates a thread which is called the main thread. Java allows the creation of several threads using either extending the thread class or implementing the Runnable interface.
  • OOPs Concepts: Java follows various OOPs concepts , namely abstraction, encapsulation, inheritance, object-oriented, and polymorphism
  • Platform Independency: Java makes use of the Java Virtual Machine or JVM, which allows a single Java program to operate on multiple platforms without any modifications.

You may want to check out detailed explanations of Java features here . 

4. How does Java enable high performance?

In Just-in-Time compilation, the required code is executed at run time. Typically, it involves translating bytecode into machine code and then executing it directly. It allows for high performance. The JIT compiler is enabled by default in Java and gets activated as soon as a method is called. 

It then compiles the bytecode of the Java method into native machine code. 

After that, the JVM calls the compiled code directly instead of interpreting it.

5. What are the differences between JVM, JRE, and JDK?

6. what is the jit compiler.

JIT compiler runs after the program is executed and compiles the code into a faster form, hosting the CPU's native instructing set. JIT can access dynamic runtime information, whereas a standard compiler doesn't and can make better optimizations like inlining functions that are used frequently. 

7. What are Java IDEs?

A Java IDE is a software that allows Java developers to easily write as well as debug Java programs. It is basically a collection of various programming tools, accessible via a single interface, and several helpful features, such as code completion and syntax highlighting. 

Codenvy, Eclipse, and NetBeans are some of the most popular Java IDEs .

8. Java is a platform-independent language. Why?

Java does not depend on any particular hardware or software because it is compiled by the compiler and then converted into byte code. Byte code is platform-independent and can run on multiple systems. The only requirement is that Java needs a runtime environment, i.e., JRE, which is a set of tools used for developing Java applications.

9. Explain Typecasting.

The concept of assigning a variable of one data type to a variable of another data type. This is not possible for the boolean data type. There are two types: implicit and explicit.

10. What are the different types of typecasting?

types of typecasting

The different types of typecasting are:

  • Implicit: Storing values from a smaller data type to the larger data type. It is automatically done by the compiler.
  • Explicit: Storing the value of a larger data type into a smaller data type. This results in information loss:
  • Truncation: While converting a value from a larger data type to a smaller data type, the extra data will be truncated. This code example explains it : 

After execution, the variable i will contain only 3 and not the decimal portion. 

  • Out of Range: Typecasting does not allow assigning value more than its range; if that happens then the data is lost in such cases. This code example explains it: 

long l = 123456789;

byte b = ( byte ) l; // byte is of not the same range as long so there will be loss of data.

11. Explain access modifiers in Java.

Access modifiers are predefined keywords in Java that are used to restrict the access of a class, method, constructor, and data member in another class. Java supports four access modifiers:

12. What are the default values for local variables?

The local variables are not initialized to any default value, neither primitives nor object references.

OOPs Java Interview Questions

13. what is object-oriented programming .

OOPs is a programming paradigm centered around objects rather than functions. It is not a tool or a programming language, it is a paradigm that was designed to overcome the flaws of procedural programming . 

There are many languages that follow OOPs concepts — some popular ones are Java, Python, and Ruby. Some frameworks also follow OOPs concepts, such as Angular.

14. Explain the OOPs concepts.

The following are the various OOPS Concepts:

  • Abstraction: Representing essential features without the need to give out background details. The technique is used for creating a new suitable data type for some specific application.
  • Aggregation: All objects have their separate lifecycle, but ownership is present. No child object can belong to some other object except for the parent object.
  • Association: The relationship between two objects, where each object has its separate lifecycle. There is no ownership.
  • Class: A group of similar entities.
  • Composition: Also called the death relationship, it is a specialized form of aggregation. Child objects don't have a lifecycle. As such, they automatically get deleted if the associated parent object is deleted.
  • Encapsulation: Refers to the wrapping up of data and code into a single entity. This allows the variables of a class to be only accessible by the parent class and no other classes.
  • Inheritance: When an object acquires the properties of some other object, it is called inheritance. It results in the formation of a parent-child relationship amongst classes involved. This offers a robust and natural mechanism of organizing and structuring software.
  • Object: Denotes an instance of a class. Any class can have multiple instances. An object contains the data as well as the method that will operate on the data
  • Polymorphism: Refers to the ability of a method, object, or variable to assume several forms.

Decision Making Java Interview Questions

15. Differentiate between break and continue.

Classes, objects, and methods java interview questions, 16. what is an object.

An instance of a Java class is known as an object. Two important properties of a Java object are behavior and state . An object is created as soon as the JVM comes across the new keyword.

17. Define classes in Java. 

A class is a collection of objects of similar data types. Classes are user-defined data types and behave like built-in types of a programming language. 

Syntax of a class: 

Example of Class:

18. What are static methods and variables?

A class has two sections: one declares variables, and the other declares methods. These are called instance variables and instance methods, respectively. They are termed so because every time a class is instantiated, a new copy of each of them is created. 

Variables and methods can be created that are common to all objects and accessed without using a particular object by declaring them static. Static members are also available to be used by other classes and methods. 

19. What do you mean by Constructor?

A constructor is a method that has the same name as that of the class to which it belongs. As soon as a new object is created, a constructor corresponding to the class gets invoked. Although the user can explicitly create a constructor, it is created on its own as soon as a class is created. This is known as the default constructor. Constructors can be overloaded.

If an explicitly-created constructor has a parameter, then it is necessary to create another constructor without a parameter.

20. What are local variables and instance variables?

Variables that are only accessible to the method or code block in which they are declared are known as local variables. Instance variables, on the other hand, are accessible to all methods in a class. 

While local variables are declared inside a method or a code block, instance variables are declared inside a class but outside a method. Even when not assigned, instance variables have a value that can be null, 0, 0.0, or false. This isn't the case with local variables that need to be assigned a value, where failing to assign a value will yield an error. Local variables are automatically created when a method is called and destroyed as soon as the method exits. For creating instance variables, the new keyword must be used.

21. What is Method Overriding?

Method Overriding

Method overriding in Java allows a subclass to offer a specific implementation of a method that has already been provided by its parent or superclass. Method overriding happens if the subclass method and the Superclass method have:

  • The same name
  • The same argument
  • The same return type

22. What is Overloading?

Overloading is the phenomenon when two or more different methods (method overloading) or operators (operator overloading) have the same representation. For example, the + operator adds two integer values but concatenates two strings. Similarly, an overloaded function called Add can be used for two purposes

  • To add two integers
  • To concatenate two strings

Unlike method overriding, method overloading requires two overloaded methods to have the same name but different arguments. The overloaded functions may or may not have different return types.

23. What role does the final keyword play in Java? What impact does it have on a variable, method, and class?

The final keyword in Java is a non-access modifier that applies only to a class, method, or variable. It serves a different purpose based on the context where it is used.

  • With a class: When a class is declared as final, then it is disabled from being subclassed i.e., no class can extend the final class.
  • With a method: Any method accompanying the final keyword is restricted from being overridden by the subclass.
  • With a variable: A variable followed by the final keyword is not able to change the value that it holds during the program execution. So, it behaves like a constant.

Arrays, Strings and Vectors Java Interview Questions

24. draw a comparison between array and arraylist..

An array necessitates stating the size during the time of declaration, while an array list doesn't necessarily require size as it changes size dynamically. To put an object into an array, there is the need to specify the index. However, no such requirement is in place for an array list. While an array list is parameterized, an array is not parameterized.

25. What are the differences between String, Stringbuilder, and Stringbuffer?

String variables are stored in a constant string pool. With the change in the string reference, it becomes impossible to delete the old value. For example, if a string has stored a value "Old," then adding the new value "New" will not delete the old value. It will still be there, however, in a dormant state. In a Stringbuffer, values are stored in a stack. With the change in the string reference, the new value replaces the older value. The Stringbuffer is synchronized (and therefore, thread-safe) and offers slower performance than the StringBuilder, which is also a Stringbuffer but is not synchronized. Hence, performance is faster in Stringbuilder than the Stringbuffer.

26. What is the String Pool?

The string pool is a collection of strings stored in the heap memory refers to. Whenever a new object is created, it is checked if it is already present in the string pool. If it is already present, then the same reference is returned to the variable, otherwise a new object is created in the string pool, and the respective reference is returned.

  • Advanced Java Interview Questions

Interfaces and Abstract Classes Java Interview Questions

27. what do you know about interfaces.

A Java interface is a template that has only method declarations and not method implementations. It is a workaround for achieving multiple inheritances in Java. Some worth remembering important points regarding Java interfaces are:

  • A class that implements the interface must provide an implementation for all methods declared in the interface.
  • All methods in an interface are internally public abstract void.
  • All variables in an interface are internally public static final.
  • Classes do not extend but implement interfaces.

28. How is an Abstract class different from an Interface?

There are several differences between an Abstract class and an Interface in Java, summed up as follows:

  • Constituents: An abstract class contains instance variables, whereas an interface can contain only constants.
  • Constructor and Instantiation: While an interface has neither a constructor nor it can be instantiated, an abstract class can have a default constructor that is called whenever the concrete subclass is instantiated.
  • Implementation of Methods – All classes that implement the interface need to provide an implementation for all the methods contained by it. A class that extends the abstract class, however, doesn't require implementing all the methods contained in it. Only abstract methods need to be implemented in the concrete subclass.
  • Type of Methods: Any abstract class has both abstract as well as non-abstract methods. Interface, on the other hand, has only a single abstract method.

29. Please explain Abstract class and Abstract method.

An abstract class in Java is a class that can't be instantiated. Such a class is typically used for providing a base for subclasses to extend as well as implementing the abstract methods and overriding or using the implemented methods defined in the abstract class. 

To create an abstract class, it needs to be followed by the abstract keyword. Any abstract class can have both abstract as well as non-abstract methods. A method in Java that only has the declaration and not implementation is known as an abstract method. Also, an abstract method name is followed by the abstract keyword. Any concrete subclass that extends the abstract class must provide an implementation for abstract methods.

30. What is multiple inheritance? Does Java support multiple inheritance? If not, how can it be achieved?

If a subclass or child class has two parent classes, that means it inherits the properties from two base classes; it has multiple inheritances. Java does not have multiple inheritances as in case the parent classes have the same method names. Then at runtime, it becomes ambiguous, and the compiler is unable to decide which method to execute from the child class.

Packages Java Interview Questions

31. what are packages in java state some advantages..

packages in Java

Packages are Java's way of grouping a variety of classes and/or interfaces together. The functionality of the objects decides how they are grouped. Packagers act as "containers" for classes.

Enlisted below are the advantages of Packages:

  • Classes of other programs can be reused.
  • Two classes with the same can exist in two different packages.
  • Packages can hide classes, thus denying access to certain programs and classes meant for internal use only.
  • They also separate design from coding.

Multithreading Java Interview Questions

32. how do you make a thread in java give examples..

To make a thread in Java, there are two options:

  • Extend the Thread Class : The thread is available in the java.lang.Thread class. To make a thread, you need to extend a thread class and override the run method. For example,

A disadvantage of using the thread class is that it becomes impossible to extend any other classes.

Nonetheless, it is possible to overload the run() method in the class

  • Implement Runnable Interface: Another way of making a thread in Java is by implementing a runnable interface. For doing so, there is the need to provide the implementation for the run() method that is defined as follows:

33. Why do we use the yield() method?

The yield() method belongs to the thread class. It transfers the currently running thread to a runnable state and also allows the other threads to execute. In other words, it gives equal priority threads a chance to run. Because yield() is a static method, it does not release any lock.

34. Explain the thread lifecycle in Java.

thread lifecycle in Java.

The thread lifecycle has the following states and follows the following order:

  • New: In the very first state of the thread lifecycle, the thread instance is created, and the start() method is yet to be invoked. The thread is considered alive now.
  • Runnable: After invoking the start() method, but before invoking the run() method, a thread is in the runnable state. A thread can also return to the runnable state from waiting or sleeping.
  • Running: The thread enters the running state after the run() method is invoked. This is when the thread begins execution.
  • Non-Runnable: Although the thread is alive, it is not able to run. Typically, it returns to the runnable state after some time.
  • Terminated: The thread enters the terminated state once the run() method completes its execution. It is not alive now.

35. When is the Runnable interface preferred over thread class and vice-versa?

In Java, it is possible to extend only one class. Hence, the thread class is only extended when no other class needs to be extended. If it is required for a class to extend some other class than the thread class, then we need to use the Runnable interface.

36. Draw a comparison between notify() and notifyAll() methods.

The notify() method is used for sending a signal to wake up a single thread in the waiting pool. Contrarily, the notifyAll() method is used for sending a signal to wake up all threads in a waiting pool.

37. How will you distinguish processes from threads?

There are several fundamental differences between a process and a thread, stated as follows:

  • Definition: A process is an executing instance of a program whereas, a thread is a subset of a process.
  • Changes: A change made to the parent process doesn't affect child processes. However, a change in the main thread can yield changes in the behavior of other threads of the same process.
  • Communication – While processes require inter-process communication for communicating with sibling processes, threads can directly communicate with other threads belonging to the same process.
  • Control: Processes are controlled by the operating system and can control only child processes. On the contrary, threads are controlled by the programmer and are capable of exercising control over threads of the same process to which they belong.
  • Dependence: Processes are independent entities while threads are dependent entities
  • Memory: Threads run in shared memory spaces, but processes run in separate memory spaces.

38. What is the join() method? Give an example.

We use the join() method for joining one thread with the end of the currently running thread. It is a non-static method and has an overloaded version. Consider the example below:

The main thread starts execution in the example mentioned above. As soon as the execution reaches the code t.start(), then the thread t starts its stack for execution. The JVM switches between the main thread and the thread there. Once the execution reaches the t.join(), then the thread t alone is executed and allowed to complete its task. Afterwards, the main thread resumes execution.

39. How do you make a thread stop in Java?

There are three methods in Java to stop the execution of a thread:

  • Blocking: This method is used to put the thread in a blocked state. The execution resumes as soon as the condition of the blocking is met. For instance, the ServerSocket.accept() is a blocking method that listens for incoming socket connections and resumes the blocked thread only when a connection is made.
  • Sleeping: This method is used for delaying the execution of the thread for some time. A thread upon which the sleep() method is used is said to enter the sleep state. It enters the runnable state as soon as it wakes up i.e., the sleep state is finished. The time for which the thread needs to enter the sleep state is mentioned inside the braces of the sleep() method. It is a static method.
  • Waiting: Although it can be called on any Java object, the wait() method can only be called from a synchronized block.

Exception Handling Java Interview Questions

40. what are the various types of exceptions how do you handle them.

Java has provision for two types of exceptions:

  • Checked Exceptions: Classes that extend the Throwable class, except Runtime exception and Error, are called checked exceptions. Such exceptions are checked by the compiler during the compile time. These types of exceptions must either have appropriate try/catch blocks or be declared using the throws keyword. ClassNotFoundException is a checked exception.
  • Unchecked Exceptions: Such exceptions aren't checked by the compiler during the compile time. As such, the compiler doesn't necessitate handling unchecked exceptions. Arithmetic Exception and ArrayIndexOutOfBounds Exception are unchecked exceptions.

Exceptions in Java are handled in two ways:

Declaring the throws keyword: We can declare the exception using throws keyword at the end of the method. For example:

Using try/catch: Any code segment that is expected to yield an exception is surrounded by the try block. Upon the occurrence of the exception, it is caught by the catch block that follows the try block. For example:

41. Draw the Java Exception Hierarchy.

Java Exception Hierarchy

42. Is it possible to write multiple catch blocks under a single try block?

Yes, it is possible to write several catch blocks under a single try block. However, the approach needs to be from specific to general. The following example demonstrates it:

43. How does the throw keyword differ from the throws keyword?

While the throws keyword allows declaring an exception, the throw keyword is used to explicitly throw an exception. 

Checked exceptions can't be propagated with throw only, but throws allow doing so without the need for anything else. 

The throws keyword is followed by a class, whereas the throw keyword is followed by an instance. The throw keyword is used within the method, but the throws keyword is used with the method signature. 

Furthermore, it is not possible to throw multiple exceptions, but it is possible to declare multiple exceptions.

44. Explain various exceptions handling keywords in Java.

There are two crucial exception handling keywords in Java, followed by the third keyword final, which may or may not be used after handling exceptions.

If and when a code segment has chances of having an abnormality or an error, it is placed within a try block. When the exception is raised, it is handled and caught by the catch block.

The try block must have a catch() or a final() or both blocks after it.

When an exception is raised in the try block, it is handled in the catch block.

This block is executed regardless of the exception. It can be placed either after try{} or catch {} block.

45. Explain exception propagation.

The method at the top of the stack throws an exception if it is not caught. It moves to the next method and goes on until caught.

The stack of the above code is:

If an exception occurred in the add() method is not caught, then it moves to the method addition(). It is then moved to the main() method, where the flow of execution stops. It is called Exception Propagation.

File Handling Java Interview Questions

46. is an empty file name with .java extension a valid file name.

Yes, Java permits us to save our java file by .java only. It is compiled by javac and run by the java class name. Here’s an example:

To compile: javac.java

To run: Java Any

Collections Java Interview Questions

47. what are collections what are their constituents.

A group of objects in Java is known as collections. Java.util package contains, along with date and time facilities, internationalization, legacy collection classes, etc., the various classes and interfaces for collecting. Alternatively, collections can be considered as a framework designed for storing the objects and manipulating the design in which the objects are stored. You can use collections to perform the following operations on objects:

  • Manipulation

Following are the various constituents of the collections framework:

  • Classes: Array List, Linked List, Lists, and Vector
  • Interfaces: Collection, List, Map, Queue, Set, Sorted Map, and Sorted Set
  • Maps: HashMap, HashTable, LinkedHashMap, and TreeMap
  • Queues: Priority Queue
  • Sets: Hash Set, Linked Hash Set, and Tree Set

48. How do you differentiate HashMap and HashTable?

HashMap in Java is a map-based collection class, used for storing key & value pairs. It is denoted as HashMap<Key, Value> or HashMap<K, V> HashTable is an array of a list, where each list is called a bucket. 

Values contained in a HashTable are unique and depend on the key. Methods are not synchronized in HashMap, while key methods are synchronized in HashTable. 

However, HashMap doesn't have thread safety, while HashTable has the same. 

For iterating values, HashMap uses an iterator and HashTable uses an enumerator. HashTable doesn't allow anything that is null, while HashMap allows one null key and several null values. 

In terms of performance, HashTable is slow. Comparatively, HashMap is faster.

49. What is a Map and what are the types?

A Java Map is an object that maps keys to values. It can't contain duplicate keys, and each key can map to only one value. In order to determine whether two keys are the same or distinct, Map makes use of the equals() method. There are 4 types of Map in Java, described as follows:

  • HashMap: It is an unordered and unsorted map and hence, is a good choice when there is no emphasis on the order. A HashMap allows one null key and multiple null values and doesn't maintain any insertion order.
  • HashTable: Doesn't allow anything null and has methods that are synchronized. As it allows for thread safety, the performance is slow.
  • LinkedHashMap: Slower than a HashMap but maintains insertion order and has a faster iteration.
  • TreeMap: A sorted Map providing support for constructing a sort order using a constructor.

50. What is a Priority Queue?

A priority queue, like a regular queue, is an abstract data type, but it has a priority associated with each element contained by it. 

The element with the high priority is served before the element with low priority in a priority queue. Elements in a priority queue are ordered either according to the comparator or naturally. The order of the elements in a priority queue represents their relative priority.

51. What is a Set? Explain the types in Java Collections.

In Java, a set is a collection of unique objects. It uses the equals() method to determine whether two objects are the same or not. The various types of set in Java Collections are:

  • Hash Set: An unordered and unsorted set that uses the hash code of the object for adding values. Used when the order of the collection isn't important
  • Linked Hash Set: This is an ordered version of the hash set that maintains a doubly-linked list of all the elements. Used when iteration order is mandatory. Insertion order is the same as that of how elements are added to the Set.
  • Tree Set: One of the two sorted collections in Java, it uses Read-Black tree structure and ensures that the elements are present in the ascending order.

52. What is ordered and sorted when it comes to collections?

  • Ordered: Values are stored in a collection in a specific order, but the order is independent of the value. Example: List
  • Sorted: The collection has an order which is dependent on the value of an element. Example: SortedSet

Miscellaneous Java Interview Questions 

53. what are the various types of garbage collectors in java.

The Java programming language has four types of garbage collectors:

  • Serial Garbage Collector: Using only a single thread for garbage collection, the serial garbage collector works by holding all the application threads. It is designed especially for single-threaded environments. Because serial garbage collector freezes all application threads while performing garbage collection, it is most suitable for command-line programs only. For using the serial garbage collector, one needs to turn on the -XX:+UseSerialGC JVM argument.
  • Parallel Garbage Collector: Also known as the throughput collector, the parallel garbage collector is the default garbage collector of the JVM. It uses multiple threads for garbage collection, and like a serial garbage collector freezes all application threads during garbage collection.
  • CMS Garbage Collector: Short for Concurrent Mark Sweep, CMS garbage collector uses multiple threads for scanning the heap memory for marking instances for eviction, followed by sweeping the marked instances. There are only two scenarios when the CMS garbage collector holds all the application threads:
  • When marking the referenced objects in the tenured generation space.
  • If there is a change in the heap memory while performing the garbage collection, CMS garbage collector ensures better application throughput over parallel garbage collectors by using more CPU resources. For using the CMS garbage collector, the XX:+USeParNewGC JVM argument needs to be turned on.
  • G1 Garbage Collector: Used for large heap memory areas, G1 garbage collector works by separating the heap memory into multiple regions and then executing garbage collection in them in parallel. Unlike the CMS garbage collector that compacts the memory on STW (Stop The World) situations , G1 garbage collector compacts the free heap space right after reclaiming the memory. Also, the G1 garbage collector prioritizes the region with the most garbage. Turning on the –XX:+UseG1GC JVM argument is required for using the G1 garbage collector.

54. What do you understand by synchronization? What is its most significant disadvantage?

If several threads try to access a single block of code, then there is an increased chance of producing inaccurate results. Synchronization is used to prevent this. Using the synchronization keyword makes a thread need a key to access the synchronized code. Simply, synchronization allows only one thread to access a block of code at a time. Each Java object has a lock, and every lock has only one key. A thread can access a synchronized method only if it can get the key to the lock of the object. The following example demonstrates synchronization:

Note : It is recommended to avoid implementing synchronization for all methods. This is because when only one thread can access the synchronized code, the next thread needs to wait. Consequently, it results in slower performance of the program.

55. What is the difference between execute(), executeQuery(), and executeUpdate()?

  • execute(): Used for executing an SQL query. It returns TRUE if the result is a ResultSet, like running Select queries, and FALSE if the result is not a ResultSet, such as running an Insert or an Update query.
  • executeQuery(): Used for executing Select queries. It returns the ResultSet, which is not null, even if no records are matching the query. The executeQuery() method must be used when executing select queries so that it throws the java.sql.SQLException with the 'executeQuery method cannot be used for update' message when someone tries to execute an Insert or Update statement.
  • executeUpdate(): Used for executing Delete/Insert/Update statements or DDL statements that return nothing. The output varies depending on whether the statements are Data Manipulation Language (DML) statements or Data Definition Language (DDL) statements. The output is an integer and equals the total row count for the former case, and 0 for the latter case.

Note : The execute() method needs to be used only in a scenario when there is no certainty about the type of statement. In all other cases, either use executeQuery() or executeUpdate() method.

56. Provide an example of the Hibernate architecture.

Hibernate architecture

57. Could you demonstrate how to delete a cookie in JSP with a code example?

The following code demonstrates deleting a cookie in JSP:

58. Write suitable code examples to demonstrate the use of final, final, and finalize.

Final:  The final keyword is used for restricting a class, method, and variable. A final class can't be inherited, a final method is disabled from overriding, and a final variable becomes a constant i.e., its value can't be changed.

Finally: Any code inside the final block will be executed, irrespective of whether an exception is handled or not.

Finalize: The finalize method performs the clean up just before the object is garbage collected.

59. What purpose does the Volatile variable serve?

The value stored in a volatile variable is not read from the thread's cache memory but from the main memory. Volatile variables are primarily used during synchronization.

60. Please compare serialization and deserialization.

Serialization is the process by which Java objects are converted into the byte stream. 

Deserialization is the exact opposite process of serialization where Java objects are retrieved from the byte stream.

 A Java object is serialized by writing it to an ObjectOutputStream and deserialized by reading it from an ObjectInputStream.

61. What is OutOfMemoryError?

Typically, the OutOfMemoryError exception is thrown when the JVM is not able to allocate an object due to running out of memory. In such a situation, no memory could be reclaimed by the garbage collector. 

There can be several reasons that result in the OutOfMemoryError exception, of which the most notable ones are:

  • Holding objects for too long
  • Trying to process too much data at the same time
  • Using a third-party library that caches strings
  • Using an application server that doesn't perform a memory cleanup post the deployment
  • When a native allocation can't be satisfied

62. Explain public static void main(String args[ ]) in Java

The execution Java program starts with public static void main(String args[ ]), also called the main() method.

  • public: It is an access modifier defining the accessibility of the class or method. Any class can access the main() method defined public in the program.
  • static: The keyword indicates the variable, or the method is a class method. The method main() is made static so that it can be accessed without creating the instance of the class. When the method main() is not made static, the compiler throws an error because the main() is called by the JVM before any objects are made, and only static methods can be directly invoked via the class.
  • void: It is the return type of the method. Void defines the method that does not return any type of value.
  • main: JVM searches this method when starting the execution of any program, with the particular signature only.
  • String args[]: The parameter passed to the main method.

Java Programming Masterclass Updated to Java 17

63. What are wrapper classes in Java?

Wrapper classes are responsible for converting the Java primitives into the reference types (objects). A class is dedicated to every primitive data type. They are known as wrapper classes because they wrap the primitive data type into an object of that class. It is present in the Java.lang package. The table below displays the different primitive types and wrapper classes.

64. Explain the concept of boxing, unboxing, autoboxing, and auto unboxing.

  • Boxing: The concept of putting a primitive value inside an object is called boxing.
  • Unboxing: Getting the primitive value from the object.
  • Autoboxing: Assigning a value directly to an integer object.
  • Auto unboxing: Getting the primitive value directly into the integer object.

65. Define the Singleton class. How can a class be made Singleton?

A Singleton class allows only one instance of the class to be created. A class can be made singleton with the following steps:

  • Creating a static instance of the class with the class.
  • By not allowing the user to create an instance with default constructor by defining a private constructor.
  • Create a static method to return the object of an instance of A.

66. What if the public static void is replaced by static public void, will the program still run?

Yes, the program would compile and run without any errors as the order of the specifiers doesn't matter.

67. What is the difference between == and equals()?

68. why don't we use pointers in java.

Pointers are considered to be unsafe, and increase the complexity of the program, adding the concept of pointers can be contradicting. Also, JVM is responsible for implicit memory allocation; thus, to avoid direct access to memory by the user, pointers are discouraged in Java.

69. What is the difference between this() and super()?

Java coding interview questions .

Apart from having good knowledge about concepts of Java programming, you are also tested for your skills in coding in Java programming language. The following are Java coding interview questions that are relevant for freshers and are quite popular amongst Java programming interviews.

70. Take a look at the two code snippets below. What is the important difference between the two?

Code snippet i. is an example of method overloading while the code snippet ii. demonstrates method overriding.

71. Write a program for string reversal without using an inbuilt function.

72. write a program to delete duplicates from an array., 73. write a program to reverse a number., 74. write a program that implements binary search., 75. write a program to check if a number is prime., 76. write a program to print fibonacci series., 77. write a program to check if the given string is a palindrome., 78. write a program to print the following pattern., 79. write a program to swap two numbers., 80. write a program to check if the given number is an armstrong number..

These core Java Interview Questions and Java Programming Interview Questions are a great way to prepare you for the interview. Review the answers, including the coding examples, and put your best foot forward.

Please note that we also provided a PDF for your preparation so that you can download and learn and prepare on the go: 

Download Java Interview Questions PDF

Prefer on-demand videos? Check out this course for further reading and preparation for a Java-based interview: Java Interview Guides: 200+ Interview Question and Answer

Otherwise, we recommend this book to help you succeed in your future Java interviews: Elements of Programming Interviews in Java: The insider guide second edition

  • Frequently Asked Questions

1. What are the basic Java questions asked in an interview?

There are several basic Java interview questions that can appear in an interview. Look at the ones we’ve listed above to get a sense of them.

2. How should I prepare for a Java interview?

You should prepare for a Java interview by learning both the theory and practicing coding. There are several related questions above.

3. What are the advanced Java interview questions?

Advanced Java interview questions can be of many kinds, including both theory and coding-based questions. Check out the list of Java programming questions above to see what they are like.

People are also reading:

  • Best Java Courses
  • Top 10 Java Certifications
  • Best Java Books
  • Best Java Projects
  • Programming Interview Questions
  • Core Java Cheatsheet - Introduction to Programming in Java
  • Difference between Java vs Javascript
  • Top 10 Java Frameworks
  • Best Way to Learn Java
  • Constructor in Java 
  • Prime Number Program in Java

problem solving interview questions for java

Simran works at Hackr as a technical writer. The graduate in MS Computer Science from the well known CS hub, aka Silicon Valley, is also an editor of the website. She enjoys writing about any tech topic, including programming, algorithms, cloud, data science, and AI. Traveling, sketching, and gardening are the hobbies that interest her.

Subscribe to our Newsletter for Articles, News, & Jobs.

Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.

In this article

  • Top 48 Networking Interview Questions and Answers in 2024 Computer Networks Career Development Interview Questions
  • Top 20 REST API Interview Questions & Answers [2024] Web Development Career Development Interview Questions
  • How to Extract a Java Substring [with Code Examples] Java

Please login to leave comments

Always be in the loop.

Get news once a week, and don't worry — no spam.

{{ errors }}

{{ message }}

  • Help center
  • We ❤️ Feedback
  • Advertise / Partner
  • Write for us
  • Privacy Policy
  • Cookie Policy
  • Change Privacy Settings
  • Disclosure Policy
  • Terms and Conditions
  • Refund Policy

Disclosure: This page may contain affliate links, meaning when you click the links and make a purchase, we receive a commission.

50 Java Interview Questions and Answers in 2024

Explore essential Java Developers interview questions

Java is a versatile, object-oriented programming language designed for cross-platform compatibility and used in various computing environments, from enterprise applications to mobile devices. The necessity for Java Interview Questions lies in their ability to evaluate a candidate's technical skill set, practical problem-solving abilities, and up-to-date knowledge of the language. These questions have limitations, including a focus on theoretical knowledge and a neglect of soft skills assessment.

Java's operation across systems is due to its "write once, run anywhere" (WORA) philosophy, facilitated by the Java Virtual Machine (JVM). Testing in Java involves frameworks like JUnit for unit testing and Selenium for end-to-end testing, ensuring application robustness. Java developers should possess a strong understanding of Java fundamentals, frameworks, database management, and front-end technologies, accompanied by critical soft skills.

Java's object-oriented structure, platform independence, and automatic memory management set it apart from procedural languages like C, while its execution environment and use cases differ significantly from those of JavaScript. These distinctions underscore Java's unique position in the programming world and the importance of nuanced understanding in professional environments.

What are Java Interview Questions For Freshers?

Java interview questions for freshers cover fundamental concepts and basic knowledge areas that are essential for beginners in Java programming. Java interview questions aim to assess a candidate's understanding of key Java concepts such as variables, data types, control structures, object-oriented programming principles, and basic Java libraries.

These questions serve as a foundation for building the Java programming skills of freshers. Mastering these fundamental concepts is crucial as they provide the basis for more advanced discussions and problem-solving in Java development. Having a strong grasp of these core concepts will boost a fresher's confidence and enable them to tackle more complex Java topics effectively.

Some of the most important Java interview questions that are asked to freshers are listed below.

1. What is Java?

View Answer

Hide Answer

Java is a high-level, object-oriented programming language known for its platform independence, robustness, and versatility. It is widely used for developing a variety of software applications, from web and mobile applications to enterprise-level systems. Java programs are compiled into bytecode, which can run on any platform with a Java Virtual Machine (JVM), making it a portable and cross-platform language.

2. Why is Java so popular?

Java is popular due to its platform independence, strong community support, extensive libraries, and scalability, making it a versatile language for various applications.

Java's platform independence allows it to run on multiple devices and operating systems, ensuring wide compatibility. Its strong community support ensures continuous development and a wealth of resources for programmers. Java’s extensive libraries and scalability make it ideal for building robust and adaptable software solutions, contributing to its enduring popularity.

3. Explain the difference between JDK, JRE, and JVM.

The difference between JDK, JRE, and JVM lies in their purpose and functionality within Java's development and runtime environments.

Java Development Kit (JDK) is the complete Java development package with tools for developing, debugging, and monitoring Java applications. JDK includes JRE and development tools like compilers and debuggers necessary for creating Java applications.

Java Runtime Environment (JRE) provides the libraries, Java Virtual Machine (JVM) and other components to run applications written in Java, but lacks the development tools to create new ones. It's essentially a subset of JDK, tailored for users to run Java programs.

Java Virtual Machine (JVM) is a part of both JDK and JRE. It's a virtual engine that executes Java bytecode, turning the compiled Java code into instructions that get executed on a computer's hardware. No Java application can run on a device without JVM.

4. How do you compile and run a Java program?

Compile and run a Java program by following the steps listed below.

1. Write the Program: Create Java file, e.g., `MyProgram.java`, using a text editor or IDE, and write the code.

2. Compile the Program: Open a command prompt/terminal. Navigate to the directory where the created Java file is saved, type `javac MyProgram.java` and press enter. This command compiles the Java code. If there are no errors, it generates a `MyProgram.class` file, which is the bytecode version of the program.

3. Run the Program: In the command prompt/terminal, type `java MyProgram` and press enter. This command uses the Java interpreter to run the bytecode file created in the compilation process. The Java program executes and displays the desired output in the command prompt/terminal.

5. What are the main features of Java?

The main features of Java are listed below.

  • Simplicity: Java is straightforward to use, understand, compile, debug, and learn than alternative programming languages.
  • Object-Oriented: Java allows creating modular programs and reusable code.
  • Platform-Independent: Ability to move easily from one computer system to another (write once, run anywhere).
  • Distributed computing: Java has a set of APIs that make it easy to use file systems, fetch files, and display documents over the internet.
  • Robust: Strong memory management, lack of pointers, and an automatic garbage collector.
  • Secure: Java is intended to provide a secure computing environment, having virus-free, tamper-free systems with authentication techniques based on public-key encryption.
  • Architecture-Neutral: Java compiler generates an architecture-neutral object file format, making the compiled code executable on many processors, with the presence of a Java runtime system.
  • Performance: High performance is ensured with the use of Just-In-Time compilers.
  • Multithreaded: The capability for a program to perform several tasks simultaneously within a program.
  • Dynamic: Java is capable of dynamically linking in new class libraries, methods, and objects. Also, it can determine object types at run time.

6. Describe the role of the Java ClassLoader.

The role of the Java ClassLoader is to dynamically load Java classes into the Java Virtual Machine (JVM). Java ClassLoader reads the bytecode of a class file, translates it into an instance of the class, and loads it into the JVM memory. This process allows the JVM to execute the class code, enabling Java's runtime extensibility and helping maintain the security boundaries between Java applications.

7. What are variables, and how do you declare them in Java?

Variables in Java are used to store values, such as numbers, characters, or strings, during a program's execution. Each variable has a specific type that dictates the size and layout of the variable's memory.

We need to specify the type and the identifier (name of the variable) to declare a variable in Java, with the following syntax listed below.

For example:

'int' and 'String' are data types, and 'number' and 'text' are variables. We can also initialize a variable at the time of declaration.

8. Explain the importance of data types in Java.

The importance of data types in Java lies in their ability to define the nature and size of data that can be stored in variables. Data types in Java ensure type safety, preventing unintended operations or data assignments that could lead to errors or data loss.

Java enforces a clear contract by specifying the data types, on what kind of operations can be performed, enhancing code reliability and maintainability. Data types in Java also aid in memory allocation, allowing the Java Virtual Machine (JVM) to allocate the precise amount of memory required for each variable. In essence, data types are fundamental to Java's robustness and efficiency.

9. What is the difference between a class and an object in Java?

The difference between a class and an object in Java lies in their fundamental roles and functionalities. A class is a blueprint or template that defines the structure and behaviors for entities, encapsulating data for the object and methods to manipulate that data.

An object, on the other hand, is an instance of a class and it represents a specific realization of the class.

A Java class serves as a design and Java objects are the actual entities that exist at runtime, embodying the properties and behaviors laid out in the class.

Your engineers should not be hiring. They should be coding

Help your team focus on what they were hired for. Flexiple will manage your entire hiring process and scale your tech team.

10. How is memory management handled in Java?

Memory management in Java is handled through an automatic memory management system known as garbage collection (GC). The key points to understand this are listed below.

  • Garbage Collection: Java automatically allocates and deallocates memory, and hence, developers don't manually manage memory allocation. Objects created during program execution that are no longer in use are considered garbage and are eligible for collection.
  • Heap Structure: Java's memory is primarily divided into two areas - the heap and the stack. The heap is where Java objects are stored, and this is the area that's managed by the garbage collection system.
  • Garbage Collectors: Java has several garbage collection algorithms, with the Garbage First (G1) collector being a popular choice. They work by reclaiming memory used by unreachable objects, ensuring program stability and performance.
  • JVM Tuning: Developers can tune the Java Virtual Machine (JVM) parameters to optimize how memory is managed in their applications, affecting aspects like the initial heap size, maximum heap size, and garbage collector performance.

11. What are the four fundamental principles of OOP?

The four fundamental principles of Object-Oriented Programming (OOP) are listed below.

  • Encapsulation: Encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit or class. Encapsulation also involves restricting access to some of the object's components, which is known as data hiding.
  • Inheritance: Inheritance principle allows a class (subclass/derived class) to inherit attributes and methods from another class (parent/base class). This promotes code reusability and establishes a relationship between the parent and child classes.
  • Polymorphism: Polymorphism is the ability of a single function or method to work in different ways based on the object being used. In Java, this is achieved using method overriding and overloading.
  • Abstraction: Abstraction is based on the concept of hiding the complex implementation details and showing only the essential features of an object. This simplifies complex operations, allowing the programmer to focus on interactions at a higher level.

12. Explain the concept of inheritance in Java.

Inheritance in Java is a mechanism where a new class is derived from an existing class. The derived class (child class) inherits all the features from the base class (parent class) and can have additional features of its own. The primary benefit is the ability to reuse code from the existing class, promoting code reusability and improving program structure. This relationship is expressed with the "extends" keyword.

13. Describe the difference between a class and an interface.

The difference between a class and an interface lies in their usage and characteristics.

A class is a blueprint for creating objects, containing both data (attributes) and methods (functions) to operate on the data. A class allows for both implementation and definition.

An interface only provides method declarations without any implementation. Classes can inherit from multiple interfaces, but Java does not support multiple inheritance for classes.

A class encapsulates the behavior and properties of an object, and an interface defines a contract where the implementing classes must adhere to it.

14. What is polymorphism, and how is it implemented in Java?

Polymorphism in Java is the ability of a single method or object to take on multiple forms. Polymorphism is a fundamental concept in Object-Oriented Programming (OOPs) that allows Java developers to write code that is flexible, scalable, and adaptable to different contexts.

There are two types of polymorphism in Java which are listed below.

  • Compile-time polymorphism (Static): Static Polymorphism is achieved through method overloading. These methods have the same name but different parameters (type, number, or both). The correct method to be called is determined at compile time based on the method signature.
  • Runtime polymorphism (Dynamic): Runtime Polymorphism (Dynamic) is achieved through method overriding. Here, a subclass provides a specific implementation of a method already defined in its superclass or interface. The JVM (Java Virtual Machine) determines the appropriate method to call at runtime, ensuring the correct behavior occurs even when the type of the object isn't determined until runtime.

15. How do you achieve method overloading and method overriding?

Method overloading in Java is achieved by creating multiple methods within the same class that have the same name but different parameters (either type, number, or both). Method overloading allows different ways of performing a single action, enhancing the program's readability.

Method overriding in Java occurs in two classes that have IS-A (inheritance) relationships. In this case, a subclass has the same method with the same name, same return type, and same parameters as a method in its superclass. It is used for providing a specific implementation of a method that is already present in its superclass.

Examples: Compile-time polymorphism (Method Overloading):

We have two methods named "show," but each accepts different parameters—one accepts an integer, and the other accepts a string. This is method overloading, a form of compile-time polymorphism. The method that gets called is determined by the parameter passed to the "show" method at compile-time.

Runtime polymorphism (Method Overriding):

We have a Parent class with a method "display()" and a Child class that extends Parent and overrides the "display()" method. This is method overriding, a form of runtime polymorphism. The method that gets called is determined by the object's actual class type at runtime.

16. What is encapsulation, and why is it important in Java?

Encapsulation is a fundamental Object-Oriented Programming (OOP) concept that bundles together the data (attributes) and methods (functions) into a single unit called a class, and restricts access to certain components.Encapsulation is achieved in Java using access modifiers which are private, protected, and public.

Encapsulation is important in Java because it provides a way to protect data from being accessed or modified by unauthorized parties, essentially establishing a form of data security. Java developers can ensure high data integrity and minimize the risk of unintended side effects, by bundling code into user-defined packages and controlling what is exposed through private, protected, and public access levels.

What are Java Interview Questions For Intermediates?

Java interview questions for intermediates are more advanced concepts and areas of the Java programming language. Java interview questions for intermediates are designed to probe the knowledge areas that are essential for those who have moved beyond beginner-level topics and are looking to demonstrate their capability in mid-level Java development.

These questions assess a developer's proficiency in applying Java concepts to real-world situations, designing solutions using Java's advanced features, and leveraging the extensive Java ecosystem to build robust and scalable applications. Building upon the foundational knowledge gained as a beginner, intermediates should be prepared to handle questions that tap into their experience and expertise in Java development.

Some of the most significant Java interview questions that are asked to intermediates are listed below which include topics on design patterns, advanced object-oriented programming techniques, Java frameworks, multithreading, and database connectivity.

17. Explain FailFast iterator and FailSafe iterator along with examples.

A Fail-Fast iterator is designed to throw a `ConcurrentModificationException` if a collection is modified while being iterated. Fail-Fast Iterator mechanism quickly detects and prevents concurrent modifications during iteration, ensuring iterator consistency. It is used in situations where it's crucial to detect and address concurrent modifications immediately, allowing developers to avoid unpredictable behavior and data corruption.

In the above code, an ArrayList with elements "A", "B", and "C" is created. We try to remove the element "B" while iterating using an iterator. Since ArrayList uses a FailFast iterator, the code throws a `ConcurrentModificationException` at the `list.remove("B")` line.

FailSafe iterators don't throw any exceptions if a collection is structurally modified during iteration. Instead, they work on a clone of the collection. Java’s `ConcurrentHashMap` and `CopyOnWriteArrayList` are examples of collections that use FailSafe iterators.

In the above code, an ArrayList `CopyOnWriteArrayList` with elements "A", "B", and "C" is created. We add an element "D" while iterating over the list. No exception is thrown because `CopyOnWriteArrayList` uses a FailSafe iterator and the iteration completes without any issues. However, the new element "D" will not be part of the current iteration.

18. What is Exception Handling?

Exception handling in Java is a powerful mechanism that allows the program to catch and manage runtime errors or exceptions, ensuring that the normal flow of the application isn't interrupted. Exception Handling is implemented using four keywords: "try," "catch," "throw," and "finally."

  • "Try" specifies a block where an exception can occur.
  • "catch" captures the exception.
  • "throw" is used to manually trigger exceptions.
  • "finally" creates a block of code that is always executed after a try-catch block concludes, regardless of whether an exception occurred.

This process of Exception Handling prevents the program from terminating abruptly and helps maintain its robustness and integrity.

19. How many types of exceptions can occur in a Java program?

Two main types of exceptions that occur in a Java Program are checked exceptions and unchecked exceptions.

20. What is the difference between an Error and an Exception.

The difference between an error and an exception in Java lies in their origin and handling. Errors are irrecoverable issues arising from the environment, such as system crashes, while exceptions occur during program execution and can be anticipated and recovered from. Exceptions are categorized into checked and unchecked types, whereas errors indicate severe problems not meant to be programmatically handled.

  • Origin: Errors are irrecoverable issues, arising from the environment in which a Java program runs, such as system crashes or running out of memory (e.g., `java.lang.StackOverflowError`). Exceptions are issues that occur during the execution of the program itself, which can be anticipated and recovered from, like trying to divide by zero (e.g., `java.lang.ArithmeticException`).
  • Handling: Exceptions are divided into checked exceptions (which must be explicitly caught or declared to be thrown in the method signature, such as `IOException`) and unchecked exceptions (which don't need to be explicitly handled, like `RuntimeException`).

Errors are also unchecked but are not meant to be caught or handled programmatically, as they indicate severe problems that are not recoverable by the application.

21. What is NullPointerException?

NullPointerException is a common runtime exception in Java, happening when an operation is attempted on an object reference pointing to null. It signifies an attempt to access methods or fields of a null object, prompting the Java Virtual Machine (JVM) to throw this exception due to the absence of an actual object for the operation.

22. When is the ArrayStoreException thrown?

The `ArrayStoreException` is thrown when an attempt is made to store an element of an incompatible type in an array. This exception occurs when trying to insert an object of one data type into an array that's declared to hold a different data type.

23. What is the difference between a Checked Exception and Unchecked Exception?

The difference between a checked exception and an unchecked exception in Java lies in how the compiler handles them. Let’s understand this in detail.

Examples include IOException, SQLException, etc. The programmer is required to either handle these exceptions using a try-catch block or propagate them using the 'throws' keyword.

Examples include ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. They are called unchecked exceptions because the compiler does not check at compile-time whether they have been handled or declared in the method's signature.

24. What is the difference between this() and super() in Java?

The difference between this() and super() in Java is in their usage and purpose in object-oriented programming.

  • "this()" is used within constructors to call another constructor of the same class in the context of the current object, ensuring proper initialization.
  • "super()" is used in a subclass's constructor to explicitly invoke a superclass's constructor, facilitating an inheritance hierarchy's appropriate initialization.

Both are used as the first statement in a constructor and are crucial for proper inheritance and object initialization, but they cannot be used simultaneously in the same constructor.

25. What is multitasking?

Multitasking in Java refers to the ability of an operating system to execute multiple tasks concurrently, allowing a system to run multiple applications or processes at the same time.

26. What do you mean by a Multithreaded program?

A multithreaded program in Java uses two or more threads to execute different parts of the program code simultaneously. This allows multiple operations to run concurrently, thus improving the performance and efficiency of an application, particularly in tasks demanding significant computing power or involving blocking operations.

27. What are the advantages of multithreading?

The advantages of multithreading include optimal resource utilization, enhanced performance on multi-core processors, simplified modeling of parallel processes, and improved application responsiveness. Multithreading saves time and resources by enabling concurrent execution within a single process, allowing programs to efficiently manage intensive tasks while remaining responsive to user interactions.

  • Resource Utilization: Multithreading allows optimal use of available resources, such as CPU cores, by allowing a program to perform multiple processes concurrently.
  • Improved Performance: It enables a program to run faster and perform more tasks at once, especially on multi-core processors.
  • Simplified Modeling: It simplifies the modeling of processes that are naturally parallel, such as simulations or complex calculations.
  • Better Responsiveness: Multithreading can improve the responsiveness of applications, allowing them to remain responsive to user interactions while performing intensive tasks in the background.
  • Economy: Saves time and resources by allowing the simultaneous execution of multiple threads within a single process, rather than initiating multiple processes.

28. What are the two ways in which Thread can be created?

Threads can be created by extending the thread class or by implementing the runnable interface. Below are the two ways by which Thread can be created.

1. Extending the Thread class: We create a new class that extends the `java.lang.Thread` class and override the `run()` method with the code to execute in the new thread. Then, we instantiate our class and call the `start()` method to begin execution.

2. Implementing the Runnable interface: We create a new class that implements the `java.lang.Runnable` interface, defining the `run()` method with the code to execute. We then pass an instance of our class to a `Thread` object and call the `start()` method.

Both methods achieve the same goal of setting up a new thread of execution but use different Java mechanisms (inheritance vs. implementing an interface).

29. What is a thread?

A thread in Java refers to the smallest unit of a program's execution. Thread is a lightweight, independent path of execution that enables concurrent processing within a Java application. Threads share the same memory space and resources of the parent process, allowing for efficient multitasking and parallelism.

30. Explain suspend() method under the Thread class.

The suspend() method under the Thread class is used to temporarily pause the execution of a thread in Java. Suspend() method puts the thread into a suspended state when it is called on a thread object, where it stops executing until it is resumed using the resume() method.

31. Explain the main thread under Thread class execution.

The main thread in Java, also known as the "main" method or the "main" thread of execution, is the entry point for a Java program. When you run a Java program, it starts executing in the main thread.

The main thread serves as the initial execution point for a Java application and executes the code inside the `public static void main(String[] args)` method. It creates and manages other threads in a multi-threaded Java application and is responsible for tasks like initializing the application, setting up resources, and controlling the overall flow of the program.

The main thread continues executing until the `main` method completes or explicitly terminates the program using the `System.exit()` method.

32. What is a daemon thread?

A daemon thread in Java is a background thread that runs independently of the main program and terminates when the main program exits. A daemon thread is used for tasks like garbage collection and monitoring, and it doesn't prevent the JVM from shutting down if all non-daemon threads have finished their work.

What are Java Interview Questions For Experienced?

Java interview questions for experienced professionals are designed to evaluate their in-depth knowledge and expertise in Java programming. These questions delve into advanced topics, design patterns, performance optimization, and real-world problem-solving skills. Experienced Java developers are expected to have a comprehensive understanding of Java's intricacies and be able to apply their knowledge to complex software development tasks.

Experienced Java interview questions cover a wide range of advanced topics, including garbage collection, multithreading, data structures, design patterns (such as Singleton and Factory patterns), memory management, and Java EE (Enterprise Edition) technologies. These questions are tailored to assess an experienced candidate's ability to write efficient and scalable Java code, optimize application performance, and address complex software design challenges.

Some of the most important Java interview questions that are asked to experienced candidates are listed below.

33. What is the drawback of Garbage Collection?

The main drawback of Garbage Collection is that it can introduce performance overhead. Garbage collection causes occasional pauses in program execution as it identifies and collects unused objects, which can impact real-time and latency-sensitive applications.

34. Explain the difference between a minor, major, and full garbage collection.

The difference between minor, major, and full garbage collection lies in the scope of memory they target: minor GC reclaims memory in the young generation, major GC handles the old generation, and full GC covers the entire Java heap.

  • Minor Garbage Collection: Minor garbage collection focuses on reclaiming memory in the young generation of the heap, which includes newly created objects. It identifies and collects short-lived objects that are no longer referenced. This process is quick and typically involves the "eden" and "survivor" spaces.
  • Major Garbage Collection: Major garbage collection (full “GC”) targets the entire heap, including both the young and old generations. It reclaims memory occupied by long-lived objects that have survived multiple minor garbage collections. Major GC is less frequent but can be time-consuming.
  • Full Garbage Collection: Full garbage collection is the process of collecting and reclaiming memory across the entire Java heap, including both young and old generations. It is a more comprehensive operation than major GC, ensuring that all unused objects, regardless of their age, are removed. Full GC can be resource-intensive and may lead to application pauses.

35. How will you identify major and minor garbage collections in Java?

To identify major and minor garbage collections in Java, monitor the JVM using tools like Java VisualVM, enable garbage collection logging, or leverage JMX for real-time insights. Profiling tools and APM solutions also provide detailed information about these collections.

  • Monitoring Tools: Utilize monitoring tools like Java VisualVM, JConsole, or third-party tools like VisualVM, or Grafana with Prometheus and the JVM Exporter. These tools provide real-time insights into garbage collection activities.

-XX:+PrintGCDetails -XX:+PrintGCDateStamps

This prints detailed information about garbage collection events, including major and minor collections, to the standard output or a specified log file.

  • Java Management Extensions (JMX): JMX is used to connect to the JVM remotely or locally and gather garbage collection statistics. Tools like JConsole or custom scripts are useful in this regard.
  • Profiling Tools: Profiling tools like YourKit, JProfiler, or VisualVM provide detailed insights into memory usage, garbage collection, and identify major and minor collections as part of their profiling capabilities.
  • Third-Party APM (Application Performance Monitoring): APM tools like New Relic, AppDynamics, or Dynatrace offer advanced monitoring features, including garbage collection analysis.
  • Application Logs: Implement custom logging in your Java application to record garbage collection events. This allows you to have application-specific logs that include major and minor collection information.

36. What is a memory leak, and how does it affect garbage collection?

A memory leak is a situation in software where a program neglects to release memory it has allocated but no longer requires, resulting in a gradual depletion of available memory resources. This affects garbage collection by making it inefficient, as the garbage collector cannot reclaim memory occupied by leaked objects. Over time, this can result in decreased application performance and potential system crashes.

37. What is JDBC?

Java Database Connectivity (JDBC) is an API that enables Java applications to interact with relational databases. JDBC provides a standard interface for connecting to and querying databases, allowing Java programs to send SQL queries and retrieve data from databases. JDBC serves as a bridge between Java applications and database management systems, facilitating database operations such as data retrieval, insertion, updating, and deletion.

38. What is a JDBC Driver?

A JDBC driver is a software component that facilitates communication between a Java application and a database management system (DBMS). JDBC Driver serves as a bridge that allows Java programs to interact with the database by translating Java calls into a format that the DBMS can understand.

Different types of JDBC drivers are available, including Type 1, Type 2, Type 3, and Type 4, each with its own characteristics and use cases. The choice of JDBC driver depends on factors such as performance, platform compatibility, and database vendor support.

39. What are the JDBC API components?

JDBC API components are Driver, Driver Manager, Connection, Statement, and ResultSet. These are explained in detail below.

  • Driver Manager: Manages a list of database drivers. It is used to establish a connection to the database.
  • Driver: A specific database driver implementation that allows Java applications to connect to a particular database.
  • Connection: Represents a connection to a database, allowing the execution of SQL queries and transactions.
  • Statement: Interface for executing SQL queries against the database. There are two main types: `PreparedStatement` for precompiled queries and `Statement` for simple queries.
  • ResultSet: Represents the result of a query and allows for the retrieval of data from the database.

These components form the core of the JDBC API, enabling Java applications to interact with relational databases seamlessly.

40. What is the JDBC Connection interface?

The JDBC Connection interface is a part of the Java Database Connectivity (JDBC) API, and it serves as a fundamental component for connecting Java applications to relational databases. JDBC Connection Interface provides methods to establish and manage a connection to a database, allowing developers to execute SQL queries and perform database operations from within a Java application.

41. What is the JDBC Rowset?

A JDBC Rowset is a Java object that represents a tabular data set from a database. A JDBC Rowset provides a more flexible and disconnected way to work with database records compared to traditional JDBC ResultSet.

Rowsets can be used to perform operations like sorting, filtering, and scrolling through the data without needing a continuous database connection. Rowsets are useful in scenarios where you need to work with data offline or in a disconnected environment.

42. What is the role of the JDBC DriverManager class?

The role of the JDBC DriverManager class is to manage a list of database drivers that match connection requests from Java applications to the appropriate database. JDBC DriverManager handles the establishment of connections to databases, allowing applications to communicate with various data sources smoothly.

43. Name some classes present in java.util.regex package.

The classes present in the java.util.regex package include: Pattern, Matcher, and PatternSyntaxException.

44. What are lambda expressions in Java 8?

Lambda expressions in Java 8 are a concise way to express anonymous functions (functional interfaces). Lambda expressions provide a clear and concise syntax for writing methods without the need to create a separate class. Lambda expressions are particularly useful in functional programming and can significantly improve the readability and simplicity of Java code.

45. What is the difference between "synchronized" and "volatile" in Java with respect to thread safety?

The difference between "synchronized" and "volatile" in Java with respect to thread safety is crucial. "Synchronized" is used to create a critical section where only one thread can execute at a time, ensuring mutual exclusion. It is suitable for scenarios where multiple threads need to coordinate access to a shared resource, preventing data corruption.

On the other hand, "volatile" ensures immediate visibility of changes made to a variable across all threads, preventing caching of the variable's value. “Synchronized" is ideal for complex synchronization involving critical sections, and "volatile" is suitable for simpler cases where you need to ensure visibility of a variable's value among threads.

46. Why is Garbage Collection necessary in Java?

Garbage Collection in Java is necessary because it automatically manages memory, helping to ensure that a Java program doesn't consume more memory than it needs by freeing up memory that objects are no longer using.

This process of garbage collection eliminates the need for manual memory management, reduces memory leaks, and helps maintain application performance and efficiency.

47. What are the different types of Thread Priorities in Java?

Different types of Thread Priorities in Java are specified through predefined constants. `Thread.MIN_PRIORITY` is the lowest with a value of 1, `Thread.NORM_PRIORITY` is moderate with a value of 5, and `Thread.MAX_PRIORITY` is the highest with a value of 10.

Threads can be assigned any priority value between `Thread.MIN_PRIORITY` and `Thread.MAX_PRIORITY`, inclusive. A thread inherits the priority of its parent thread, by default.

48. What is the default priority of a thread assigned by JVM?

The default priority of a thread assigned by JVM is 5 (`Thread.NORM_PRIORITY`).

49. What are the steps to connect to the database in Java?

The steps to connect to the database in Java are listed below.

  • Import the package: Include the SQL package in Java code, which contains the classes for processing database-related operations.
  • Load and Register the Driver: Load the JDBC driver specific to the database (like MySQL , Oracle, etc.) and register it so that the communication channel can be opened with the database.
  • Establish a Connection: Use the `DriverManager` class to create a Connection object, which represents a physical connection with the database.
  • Create a Statement: Once connected, you can execute queries and updates on the database. Create a Statement object for this.
  • Execute the Query: Use the created Statement to run SQL query.
  • Process Results: If the queries return results, process them. For a query that updates or alters the database, you'll confirm successful execution.
  • Close Connection: Close the ResultSet, Statement, and Connection to free up resources.

It's important to handle exceptions for error-prone statements, through try-catch-finally blocks. Also, the specifics can vary depending on the database and JDBC driver you're using.

50 What does the JDBC ResultSet interface represent?

The JDBC ResultSet interface represents a database result set generated by executing a statement that queries the database. JDBC ResultSet interface acts as an iterator to allow you to move through the retrieved data, used for reading the retrieved data and returning it in a tabular form.

What is Java?

Java is a high-level, class-based, object-oriented programming language designed to have as few implementation dependencies as possible. Java is a general-purpose programming language that is concurrent, structured for flexibility and adaptability, allowing developers to write code that would run on any device through the Java Virtual Machine (JVM).

Java is widely used for developing enterprise-scale applications, mobile applications (primarily on the Android platform), and large systems due to its stability, scalability, and maintainability.

Why are Java Interview Questions Necessary?

Java Interview Questions are necessary because of the various reasons listed below.

  • Assess Proficiency: They help interviewers evaluate a candidate's knowledge and expertise in Java, ensuring the individual is capable of handling the responsibilities that require Java skills.
  • Test Practical Skills: These questions extend beyond theoretical knowledge, testing a candidate's ability to apply Java concepts to solve real-world problems, indicative of their performance on the job.
  • Gauge Experience: The depth of Java questions asked helps determine a candidate's level of experience with the language, whether they're a beginner, intermediate, or expert.
  • Verify Problem-Solving Abilities: Coding challenges and algorithm-related questions in Java assess candidate's logical thinking and problem-solving skills, crucial for development roles.
  • Ensure Up-to-date Knowledge: Java is continuously evolving, and these questions ensure candidates are current with the latest features and best practices, confirming they can efficiently contribute to modern development projects.

How does the Interview Questions Intended for Javas Work?

Java interview questions are intended in shaping the skills and capabilities of Java developers. These questions serve as a continuous learning tool, allowing developers to stay updated with the language's evolving features and best practices. Developers deepen their understanding of Java concepts by engaging with a variety of questions, enhancing their problem-solving skills and coding proficiency.

Java questions are instrumental in interview preparation. Technical interviews often involve challenging Java problems that assess a developer's ability to apply theoretical knowledge in practical scenarios. Practicing these questions sharpens a developer's problem-solving acumen, enabling them to tackle real-world coding challenges efficiently.

Java questions serve as a benchmark for skill assessment. Regularly tackling these questions allows developers to evaluate their proficiency, identify areas for improvement, and focus their learning efforts. Java questions are not just theoretical exercises; they are dynamic tools that empower Java developers to excel in their roles, whether it be through job interviews, continuous learning, or community collaboration.

What does Java do?

Java empowers developers to create software applications that can run on any device or operating system without needing recompilation. This universality comes from Java's fundamental feature: "write once, run anywhere" (WORA), facilitated by the Java Virtual Machine (JVM), which interprets Java code into machine language for different platforms. This makes Java versatile for software development, contributing to its widespread use in areas like web development, mobile applications, enterprise solutions, and cloud computing.

Are Java developers Programmers?

Yes, Java developers are programmers. A Java developer is a programmer who specializes in using the Java programming language to develop software applications, websites, and other digital solutions. Java developers write, test, debug, and deploy code using Java and related technologies, making them skilled programmers within the context of Java development. Being a Java developer requires proficiency in programming concepts, algorithms, and software engineering principles specific to the Java language.

On What Systems Does Java Operate?

Java operates on various operating systems such as Windows, macOS, Linux, and Unix-based platforms. It is designed to be platform-independent, allowing Java applications to run seamlessly on different devices, from computers and smartphones to embedded systems and servers, without requiring modifications or recompilation.

How does Java test its applications?

Java tests its applications through a practice called unit testing, using frameworks like JUnit and TestNG. These frameworks allow developers to write code to test their code, automating the process of testing individual units of source code for correctness. Test cases are written and executed separately from the application code, ensuring each function operates as expected.

1. Unit Testing:

  • Java conducts unit testing using frameworks like JUnit and TestNG.
  • Developers write specific test cases to validate individual units of source code.
  • Automated testing tools like JUnit and TestNG execute these test cases independently from the application code.
  • This process ensures that each function and unit of code operates correctly in isolation.

2. Integration Testing:

  • Integration testing verifies the collaboration between different modules.
  • Java developers utilize tools like Mockito and PowerMock to create mock objects.
  • These mock objects simulate the behavior of complex applications with external dependencies.
  • Integration tests ensure that modules work together seamlessly as part of the larger application.

3. End-to-End Testing with Selenium:

  • Java developers employ Selenium for end-to-end system testing, specifically for web applications.
  • Selenium automates browser actions such as clicking, filling forms, and navigating between pages.
  • Automated scripts are created to simulate user interactions.
  • Selenium verifies the integrated operation of the entire system from the user's perspective, ensuring the application functions correctly in a real-world scenario.

What are the benefits of Java Interview Questions for Hiring?

The benefits of Java Interview Questions for hiring include assessing applicants' technical proficiency and problem-solving skills in Java ecosystems. The Java Interview Questions provide insights into candidates' understanding of core Java principles and their code quality standards. These questions help assess cultural fit and ongoing learning potential, essential for adapting to technological evolutions.

Benefits of Java interview questions used during the hiring process are listed below in detail.

  • Assessing Technical Proficiency: Java interview questions evaluate candidate's knowledge and experience in Java-related technologies, frameworks, and best practices.
  • Problem-Solving Skills: Interviewers can gauge a candidate's ability to solve real-world problems using Java through coding challenges and scenario-based questions.
  • Understanding of Java Principles: Questions on object-oriented programming, JVM, and memory management reveal a candidate's depth of understanding of Java's core principles.
  • Code Quality: Employers can assess the coding standards, efficiency, and readability, which are crucial for maintainability, by asking the candidates to write or review code.
  • Cultural Fit: Behavioral questions combined with technical ones help determine if a candidate's approach to coding and problem-solving aligns with the company's culture.
  • Future Learning Potential: The depth and breadth of responses can indicate a candidate's passion for Java and their potential for continuous learning and adaptation to new Java developments.

What are the limitations of Java Interview Questions for Hiring?

The limitations of Java interview questions for hiring include their theoretical nature, which doesn't gauge real-world coding efficacy, a neglect of essential soft skills, and the potential for candidates to rely on memorization rather than genuine understanding. Generic questions fail to assess role-specific competencies and inadvertently introduce bias in selection.

The limitations of Java interview questions for hiring revolve around the inability to fully assess a candidate's practical skills, on-the-job performance potential, and soft skills. Here's a concise breakdown below.

  • Theoretical Nature: Java interview questions focus on theoretical knowledge, which doesn't necessarily translate into a candidate's ability to write efficient, clean, or maintainable code in real-world scenarios.
  • Neglect of Soft Skills: These questions usually don't evaluate soft skills such as teamwork, communication, problem-solving, and resilience, which are crucial for success in a collaborative work environment.
  • Lack of Customization: Java interview questions can be generic and may not cater to the specific requirements or use-cases of the job role, thus failing to assess a candidate's competency in the niche areas needed for the position.
  • Pressure Environment: The interview setting creates pressure that causes even skilled candidates to underperform, not accurately reflecting their coding capabilities or their capacity to learn and adapt, which is relevant in the fast-evolving tech landscape.
  • Over-reliance on Memorization: Candidates mostly pass the interview stage by memorizing answers, which doesn't prove their proficiency in Java or their capability to innovate and tackle unforeseen challenges on the job.
  • Bias and Diversity Issues: The format of Java questions favor individuals with specific educational backgrounds or experiences, potentially leading to biased hiring decisions and lack of diversity within teams.

Employers are incorporating practical coding assessments, behavioral interviews, and role-specific tasks into the hiring process to ensure a holistic evaluation of Java candidates.

What skills should a Java developer possess?

The skills that a Java developer should possess include robust understanding of Java fundamentals and coding syntax, including a strong grasp of object-oriented programming (OOP) concepts, such as inheritance, encapsulation, polymorphism, and abstraction. Proficiency in Java frameworks like Spring, Hibernate, or Struts is essential, given their widespread industry adoption.

  • Java Fundamentals: A strong understanding of Java basics and coding syntax.
  • Object-Oriented Programming (OOP): Proficiency in OOP concepts such as inheritance, encapsulation, polymorphism, and abstraction.
  • Frameworks: Experience with widely-used Java frameworks like Spring, Hibernate, or Struts.
  • API Development: Adeptness in developing and managing APIs.
  • Database Management: Experience in working with SQL databases; knowledge of NoSQL databases is a plus.
  • Front-end Technologies: Familiarity with HTML, CSS, and JavaScript for full-stack development.
  • Secure Coding: Understanding principles of secure coding practices.
  • Version Control: Knowledge of version control systems like Git.
  • Build Tools: Experience with build tools such as Maven and Gradle.
  • Soft Skills: Abilities in problem-solving, debugging, analytical thinking, and effective communication for collaborative teamwork.

How does a Java Different Compare to an JavaScript Developer?

Java is different compared to JavaScript in their use cases, syntax, and execution environments.

Java is a statically typed, object-oriented language designed for long, complex applications and is used for building large-scale enterprise-level applications. Java requires compilation before execution and runs on the Java Virtual Machine (JVM), enabling a write-once-run-anywhere approach.

JavaScript is a dynamic scripting language, used to add interactivity within web browsers, enabling features like animations, pop-ups, and form submissions.

Java applications can run on any machine equipped with the JVM, but JavaScript code runs only in the client's browser, allowing for real-time user interaction without the need to communicate with the server.

The syntax and structural differences, such as Java enforcing type declaration while JavaScript does not, further highlight their distinct roles in software development.

How does a Java Different Compare to a C Language?

Java is different compared to C language due to its platform independence, object-oriented structure, and built-in memory management.

  • C Language is a procedural language, while Java is an object-oriented programming language, allowing for more complex and scalable software design through encapsulation, inheritance, and polymorphism.
  • Java's hallmark feature, "write once, run anywhere" (WORA), is possible because of the Java Virtual Machine (JVM), which enables compiled Java code (bytecode) to run on any device without recompilation, unlike C, where the compiled code is platform-specific.
  • Java eliminates explicit memory management as it features an automatic garbage collection system, preventing common memory issues prevalent in C such as buffer overflows and memory leaks. These fundamental differences illustrate how Java and C cater to different programming paradigms and application complexities.

Interview Resources

Want to upskill further through more interview questions and resources? Check out our collection of resources curated just for you.

  • Salary Insights
  • Hourly Rate Guide
  • Tech Deep-Dive
  • Interview Questions
  • Job Description
  • Certifications and Courses

Browse Flexiple's talent pool

While you build a world-class company, we help you assemble a dream tech team. Because, you deserve it.

  • Programmers
  • React Native
  • Ruby on Rails
  • Other Developers

Top 72 Swift Interview Questions

42 Advanced Java Interview Questions For Senior Developers

Java is an all-time favorite programming language of the world. According to the latest research, 90 % of Fortune 500 companies using Java, and almost all Android apps are based on Java Programming with 9 million Java developers are placed all around the world.

Q1 :   How does Garbage Collection prevent a Java application from going out of memory?

It doesn’t! Garbage Collection simply cleans up unused memory when an object goes out of scope and is no longer needed. However an application could create a huge number of large objects that causes an OutOfMemoryError .

Q2 :   What differences exist between HashMap and Hashtable ?

There are several differences between HashMap and Hashtable in Java:

Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.

Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.

One of HashMap's subclasses is LinkedHashMap , so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap . This wouldn't be as easy if you were using Hashtable .

Q3 :   What is Function Overriding and Overloading in Java?

  • Method overloading in Java occurs when two or more methods in the same class have the exact same name, but different parameters.
  • On the other hand, method overriding is defined as the case when a child class redefines the same method as a parent class. Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides.

Q4 :   What is reflection and why is it useful?

The name reflection is used to describe code which is able to inspect other code in the same system (or itself) and to make modifications at runtime.

For example, say you have an object of an unknown type in Java, and you would like to call a 'doSomething' method on it if one exists. Java's static typing system isn't really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called 'doSomething' and then call it if you want to.

Q5 :   What is the difference between Exception and Error in Java?

  • An Error "indicates serious problems that a reasonable application should not try to catch."
  • An Exception "indicates conditions that a reasonable application might want to catch."

Q6 :   What is the difference between an Interface and an Abstract class?

Java provides and supports the creation both of abstract classes and interfaces . Both implementations share some common characteristics, but they differ in the following features:

  • All methods in an interface are implicitly abstract. On the other hand, an abstract class may contain both abstract and non-abstract methods.
  • A class may implement a number of Interfaces, but can extend only one abstract class.
  • In order for a class to implement an interface, it must implement all its declared methods. However, a class may not implement all declared methods of an abstract class. Though, in this case, the sub-class must also be declared as abstract.
  • Abstract classes can implement interfaces without even providing the implementation of interface methods.
  • Variables declared in a Java interface is by default final. An abstract class may contain non-final variables.
  • Members of a Java interface are public by default. A member of an abstract class can either be private, protected or public.
  • An interface is absolutely abstract and cannot be instantiated. An abstract class also cannot be instantiated, but can be invoked if it contains a main method.

Q7 :   Can == be used on enum ?

Yes : enums have tight instance controls that allows you to use == to compare instances. Here's the guarantee provided by the language specification.

Q8 :   How can I synchornize two Java processes?

It is not possible to do something like you want in Java. Different Java applications will use different JVM's fully separating themselves into different 'blackbox'es. However, you have 2 options:

  • Use sockets (or channels). Basically one application will open the listening socket and start waiting until it receives some signal. The other application will connect there, and send signals when it had completed something. I'd say this is a preferred way used in 99.9% of applications.
  • You can call winapi from Java (on windows).

Q9 :   Is Java pass-by-reference or pass-by-value ?

Java is always pass-by-value . Unfortunately, when we pass the value of an object, we are passing the reference to it. There is no such thing as "pass-by-reference" in Java. This is confusing to beginners.

The key to understanding this is that something like

is not a Dog; it's actually a pointer to a Dog.

So when you have

you're essentially passing the address of the created Dog object to the foo method.

Q10 :   Is there anything like static class in Java?

Java has no way of making a top-level class static but you can simulate a static class like this:

  • Declare your class final - Prevents extension of the class since extending a static class makes no sense
  • Make the constructor private - Prevents instantiation by client code as it makes no sense to instantiate a static class
  • Make all the members and functions of the class static - Since the class cannot be instantiated no instance methods can be called or instance fields accessed
  • Note that the compiler will not prevent you from declaring an instance (non-static) member. The issue will only show up if you attempt to call the instance member

Q11 :   What are the differences between == and equals ?

As a reminder, it needs to be said that generally, == is NOT a viable alternative to equals . When it is, however (such as with enum), there are two important differences to consider:

  • == never throws NullPointerException
  • == is subject to type compatibility check at compile time

Q12 :   What do the ... dots in the method parameters mean?

What do the 3 dots in the following method mean?

That feature is called varargs, and it's a feature introduced in Java 5. It means that function can receive multiple String arguments:

Then, you can use the String var as an array:

Q13 :   What is static initializer ?

The static initializer is a static {} block of code inside java class, and run only one time before the constructor or main method is called. If you had to perform a complicated calculation to determine the value of x — or if its value comes from a database — a static initializer could be very useful.

Q14 :   What is a JavaBean exactly?

Basically, a "Bean" follows the standart:

  • is a serializable object (that is, it implements java.io.Serializable , and does so correctly), that
  • has "properties" whose getters and setters are just methods with certain names (like, say, getFoo() is the getter for the "Foo" property), and
  • has a public 0-arg constructor (so it can be created at will and configured by setting its properties).

There is no syntactic difference between a JavaBean and another class - a class is a JavaBean if it follows the standards.

Q15 :   What is difference between fail-fast and fail-safe ?

The Iterator's fail-safe property works with the clone of the underlying collection and thus, it is not affected by any modification in the collection. All the collection classes in java.util package are fail-fast, while the collection classes in java.util.concurrent are fail-safe. Fail-fast iterators throw a ConcurrentModificationException , while fail-safe iterator never throws such an exception.

Q16 :   What is structure of Java Heap ?

The JVM has a heap that is the runtime data area from which memory for all class instances and arrays is allocated. It is created at the JVM start-up. Heap memory for objects is reclaimed by an automatic memory management system which is known as a garbage collector. Heap memory consists of live and dead objects. Live objects are accessible by the application and will not be a subject of garbage collection. Dead objects are those which will never be accessible by the application, but have not been collected by the garbage collector yet. Such objects occupy the heap memory space until they are eventually collected by the garbage collector.

Q17 :   What is the JIT ?

The JIT is the JVM’s mechanism by which it can optimize code at runtime.

JIT means Just In Time . It is a central feature of any JVM. Among other optimizations, it can perform code inlining, lock coarsening or lock eliding, escape analysis etc.

The main benefit of the JIT is on the programmer’s side: code should be written so that it just works; if the code can be optimized at runtime, more often than not, the JIT will find a way.

Q18 :   What is the difference between throw and throws ?

The throw keyword is used to explicitly raise a exception within the program. On the contrary, the throws clause is used to indicate those exceptions that are not handled by a method. Each method must explicitly specify which exceptions does not handle, so the callers of that method can guard against possible exceptions. Finally, multiple exceptions are separated by a comma.

Q19 :   What is the main difference between StringBuffer and StringBuilder ?

StringBuffer is synchronized, StringBuilder is not. When some thing is synchronized, then multiple threads can access, and modify it with out any problem or side effect. StringBuffer is synchronized, so you can use it with multiple threads with out any problem.

StringBuilder is faster than StringBuffer because it's not synchronized. Using synchronized methods in a single thread is overkill.

Q20 :   What is the tradeoff between using an unordered array versus an ordered array ?

The major advantage of an ordered array is that the search times have time complexity of O(log n), compared to that of an unordered array, which is O (n). The disadvantage of an ordered array is that the insertion operation has a time complexity of O(n), because the elements with higher values must be moved to make room for the new element. Instead, the insertion operation for an unordered array takes constant time of O(1).

Q21 :   Why does Java have transient fields ?

The transient keyword in Java is used to indicate that a field should not be part of the serialization.

By default, all of object's variables get converted into a persistent state. In some cases, you may want to avoid persisting some variables because you don't have the need to persist those variables. So you can declare those variables as transient. If the variable is declared as transient , then it will not be persisted .

Q22 :   Does Java support default parameter values ?

No . We can use overloading instead of default parameters like:

Q23 :   Explain Marshalling and Demarshalling .

When an application wants to pass its memory objects across a network to another host or persist it to storage, the in-memory representation must be converted to a suitable format. This process is called marshalling and the revert operation is called demarshalling.

Q24 :   Explain a use case for the Builder Design Pattern

The good example is a class hierarchy that adds more parameters as it goes down the chain. At the bottom, some of the classes can have up to N parameters, N-2 of which are just being passed into the super constructor. Instead of using a particular constructor with N params we could use the Builder Design Pattern .

Consider the following example:

This lets us write code like:

Q25 :   Given two double values d1 , d2 , what is the most reliable way to test their equality ?

The most accurate way to tell whether two double values are equal to one another is to use Double.compare() and test against 0, as in:

We can't use == because of Double.NaN (literally: “Not a Number”). Consider:

will print false .

Q26 :   Is null check needed before calling instanceof ?

return false or throw a NullPointerException ?

No , a null check is not needed before using instanceof. The expression

is false if x is null .

Q27 :   Is it possible to call one constructor from another in Java?

Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how?

Yes, it is possible using this(args) :

The preferred pattern is to work from the smallest constructor to the largest like:

Q28 :   What exactly is marker interface in Java?

The marker interface in Java is an interfaces with no field or methods. In other words, it an empty interface in java is called a marker interface. An example of a marker interface is a Serializable , Clonable and Remote interface.

Marker interface is used as a tag to inform a message to the java compiler so that it can add special behaviour to the class implementing it.

Q29 :   What is Double Brace initialization in Java?

Double brace initialisation creates an anonymous class derived from the specified class (the outer braces), and provides an initialiser block within that class (the inner braces). e.g.

However, I'm not too fond of that method because what you end up with is a subclass of ArrayList which has an instance initializer, and that class is created just to create one object -- that just seems like a little bit overkill to me.

Q30 :   What is the difference between Serial and Throughput Garbage collector?

The throughput garbage collector uses a parallel version of the young generation collector and is meant to be used with applications that have medium to large data sets. On the other hand, the serial collector is usually adequate for most small applications (those requiring heaps of up to approximately 100MB on modern processors).

Q31 :   What is the difference between a synchronized method and a synchronized block ?

In Java programming, each object has a lock. A thread can acquire the lock for an object by using the synchronized keyword. The synchronized keyword can be applied in a method level (coarse grained lock) or block level of code (fine grained lock).

Q32 :   When to use LinkedList over ArrayList in Java?

LinkedList and ArrayList are two different implementations of the List interface. LinkedList implements it with a doubly-linked list.

LinkedList<E> allows for constant-time insertions or removals using iterators, but only sequential access of elements. In other words, you can walk the list forwards or backwards, but finding a position in the list takes time proportional to the size of the list.

ArrayList<E> , on the other hand, allow fast random read access, so you can grab any element in constant time. But adding or removing from anywhere but the end requires shifting all the latter elements over, either to make an opening or fill the gap.

Q33 :   Why is char[] preferred over String for passwords?

Why does String pose a threat to security when it comes to passwords? It feels inconvenient to use char[] ?

Strings are immutable . That means once you've created the String , if another process can dump memory, there's no way (aside from reflection) you can get rid of the data before garbage collection kicks in.

With an array , you can explicitly wipe the data after you're done with it. You can overwrite the array with anything you like, and the password won't be present anywhere in the system, even before garbage collection.

Q34 :   Compare volatile vs static variables in Java

Declaring a static variable in Java, means that there will be only one copy, no matter how many objects of the class are created. The variable will be accessible even with no Objects created at all. However, threads may have locally cached values of it.

When a variable is volatile and not static , there will be one variable for each Object . So, on the surface it seems there is no difference from a normal variable but totally different from static . However, even with Object fields, a thread may cache a variable value locally.

This means that if two threads update a variable of the same Object concurrently, and the variable is not declared volatile, there could be a case in which one of the thread has in cache an old value.

Even if you access a static value through multiple threads, each thread can have its local cached copy! To avoid this you can declare the variable as static volatile and this will force the thread to read each time the global value.

Q35 :   Explain what will the code return

If there is a return statement within the finally block, it will trump any other return from the regular block. That is, the following block would return false . And a return within finally ignores any exception thrown in try . Scary!

Q36 :   Provide some examples when a finally block won't be executed in Java?

Usually, finally will be called after the execution of the try or catch code blocks.

The only times finally won't be called are:

  • If you invoke System.exit()
  • If the JVM crashes first
  • If the JVM reaches an infinite loop (or some other non-interruptable, non-terminating statement) in the try or catch block
  • If the OS forcibly terminates the JVM process; e.g., kill -9 <pid> on UNIX
  • If the host system dies; e.g., power failure, hardware error, OS panic, et cetera
  • If the finally block is going to be executed by a daemon thread and all other non-daemon threads exit before finally is called

Q37 :   What does synchronized mean?

The synchronized keyword is all about different threads reading and writing to the same variables, objects and resources. The synchronized keyword is one of the tools that make your code thread safe.

synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods. Synchronized methods can't be called in the same time from multiple threads.

So simply speaking when you have two threads that are reading and writing to the same 'resource', say a variable named foo , you need to ensure that these threads access the variable in an atomic way. Without the synchronized keyword, your thread 1 may not see the change thread 2 made to foo , or worse, it may only be half changed. This would not be what you logically expect.

Q38 :   What is an efficient way to implement a singleton pattern in Java?

Since java5 use an enum :

This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.

Pre java5, the most simple case is:

Q39 :   What's the difference between SoftReference and WeakReference in Java?

  • A Strong reference is a normal reference that protects the referred object from collection by GC. i.e. Never garbage collects.
  • A Soft reference is eligible for collection by garbage collector, but probably won't be collected until its memory is needed. i.e. garbage collects before OutOfMemoryError .
  • A Weak reference is a reference that does not protect a referenced object from collection by GC. i.e. garbage collects when no Strong or Soft refs.
  • A Phantom reference is a reference to an object is phantomly referenced after it has been finalized, but before its allocated memory has been reclaimed.

Q40 :   What's wrong with Double Brace Initialization in Java?

Using Double Brace initialization is not ideal because:

  • You're creating way too many anonymous classes . For example:

... will produce these classes:

That's quite a bit of overhead for your classloader - for nothing! 2. You're potentially creating a memory leak . If you take the above code and return that map from a method, callers of that method might be unsuspectingly holding on to very heavy resources that cannot be garbage collected.

Q41 :   Why ArrayList are preferable in many more use-cases than LinkedList ?

LinkedList is almost always a (performance) bug:

  • It uses lots of small memory objects, and therefore impacts performance across the process.
  • Lots of small objects are bad for cache-locality.
  • Any indexed operation requires a traversal, i.e. has O(n) performance. This is not obvious in the source code, leading to algorithms O(n) slower than if ArrayList was used.
  • Getting good performance is tricky.
  • Even when big-O performance is the same as ArrayList , it is probably going to be significantly slower anyway.
  • It's jarring to see LinkedList in source because it is probably the wrong choice.

Q42 :   Why isn’t String‘s length() accurate?

It isn’t accurate because it will only account for the number of characters within the String . In other words, it will fail to account for code points outside of what is called the BMP (Basic Multilingual Plane), that is, code points with a value of U+10000 or greater.

The reason is historical: when Java was first defined, one of its goal was to treat all text as Unicode; but at this time, Unicode did not define code points outside of the BMP. By the time Unicode defined such code points, it was too late for char to be changed.

The correct way to count the real numbers of characters within a String, i.e. the number of code points, is either:

Rust has been Stack Overflow’s most loved language for four years in a row and emerged as a compelling language choice for both backend and system developers, offering a unique combination of memory safety, performance, concurrency without Data races...

Clean Architecture provides a clear and modular structure for building software systems, separating business rules from implementation details. It promotes maintainability by allowing for easier updates and changes to specific components without affe...

Azure Service Bus is a crucial component for Azure cloud developers as it provides reliable and scalable messaging capabilities. It enables decoupled communication between different components of a distributed system, promoting flexibility and resili...

FullStack.Cafe is a biggest hand-picked collection of top Full-Stack, Coding, Data Structures & System Design Interview Questions to land 6-figure job offer in no time.

Coded with 🧡 using React in Australia 🇦🇺

by @aershov24 , Full Stack Cafe Pty Ltd 🤙, 2018-2023

Privacy • Terms of Service • Guest Posts • Contacts • MLStack.Cafe

problem solving interview questions for java

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

Top interview problem solving questions solved in Java.

Pierre-Malak/ProblemSolving-Interview

Folders and files, repository files navigation, top problem solving questions.

  • Java 100.0%

problem solving interview questions for java

Recent Posts

Level Up Your Skills: Learn Advanced Techniques for Generative AI

Level Up Your Skills: Learn Advanced Techniques for Generative AI

by Abdul Wasay

Did you know that generative AI techniques are reshaping the world of artificial intelligence? With machine learning, deep learning, natural language processing, and neural networks at its core, generative AI has become a game-changer in various domains. The ability...

Level Up Your Leadership: Essential Skills for Senior Engineers

Level Up Your Leadership: Essential Skills for Senior Engineers

Senior software developers are really important in the tech world. They play a big part in making new ideas work and driving the industry forward. What sets them apart is not just their experience. Sure, they are skilled at coding. But they also lead their teams to...

Top 10 Code Studio Extensions to Supercharge Your React Development

Top 10 Code Studio Extensions to Supercharge Your React Development

by Editorial Team

Visual Studio Code (VS Code) has become the go-to Integrated Development Environment (IDE) for many developers due to its versatility, speed, and extensive library of extensions. These extensions can significantly enhance your productivity and streamline your React...

Top Machine Learning Projects You Can Start Today (2024 Edition) 

Top Machine Learning Projects You Can Start Today (2024 Edition) 

Machine learning (ML) is rapidly transforming the world around us, from the way we interact with technology to the decisions businesses make. As a result, the demand for skilled machine learning practitioners is booming. Machine learning projects are a great way to...

Java Coding Interview Questions

by Abdul Wasay | Mar 25, 2024

Java Coding Interview Questions You Need to Know

Did you know that Java is one of the world’s most widely used programming languages? It powers countless applications and systems, from enterprise software to Android apps. As a result, Java coding interview questions have become a crucial part of the hiring process for Java developers . If you’re aspiring to land a job as a Java developer, you must have a strong grasp of these questions.

problem solving interview questions for java

Key Takeaways:

  • Mastering Java coding interview questions is crucial for Java developers aiming to excel in interviews.
  • A strong understanding of Java coding interview questions increases your chances of success.
  • Java is widely used in various industries, making it a valuable skill for developers.
  • Preparing for common Java coding interview questions helps build your technical skills.
  • Stay updated with the latest Java features and practices to stand out in interviews.

Common Java Coding Interview Questions

Java Coding Interview

This section will explore some of the most commonly asked Java coding interview questions. These questions cover fundamental concepts that every Java developer should be familiar with. Understanding and preparing for these questions can greatly increase your chances of success in your Java coding interviews.

Write a program that prints the numbers from 1 to 100. But for multiples of three, print “Fizz” instead of the number, and for the multiples of five, print “Buzz”. For numbers that are multiples of both three and five, print “FizzBuzz”.

Palindrome Check

Write a function to determine if a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward.

Fibonacci Series

Create a program that generates the Fibonacci series up to a given number of terms. The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones.

Reverse a String

Write a function that reverses a given string. For example, if the input is “Hello”, the output should be “olleH”.

Find the Missing Number

Given an array of integers from 1 to n, one number is missing. Write a function to find the missing number in the array.

These are just a few examples of common Java coding interview questions. Practicing and familiarizing yourself with various questions to build your confidence and problem-solving skills is important.

problem solving interview questions for java

Core Java Interview Questions

When interviewing candidates for Java developer positions, assessing their understanding of core Java principles is crucial. Core Java interview questions focus on the foundational concepts of the Java programming language, ensuring that candidates possess a strong grasp of the fundamentals. This section explores essential core Java interview questions that evaluate a candidate’s knowledge and expertise in key areas.

1. What is the difference between JDK, JRE, and JVM?

The Java Development Kit (JDK) is a software development environment that provides tools, libraries, and documentation for developing Java applications. The Java Runtime Environment (JRE) is an implementation of the Java Virtual Machine (JVM) that allows you to run Java applications. The Java Virtual Machine (JVM) is an abstract machine that interprets Java bytecode, enabling platform independence by translating the bytecode into machine-specific instructions.

2. Explain the key features of object-oriented programming in Java.

Encapsulation: Bundling data and methods within a class to hide implementation details. Inheritance: Allowing classes to inherit attributes and behaviors from other classes. Polymorphism: Using a single interface to represent multiple forms. Abstraction: Providing a simplified view of complex systems by defining classes based on common characteristics.

It is essential to assess a candidate’s understanding of these core Java concepts and ability to apply them in real-world scenarios. By evaluating their responses to these interview questions, you can gauge the depth of their knowledge and experience with Java programming.

problem solving interview questions for java

The next section will explore advanced Java coding interview questions that challenge candidates with complex programming problems and advanced Java concepts.

problem solving interview questions for java

Advanced Java Coding Interview Questions

Aspiring Java developers who wish to stand out in interviews must be familiar with the common Java coding interview questions and prepared for more advanced ones. This section presents a collection of challenging Java coding questions that require a deep understanding of advanced Java concepts and principles.

1. Explain the concept of multithreading in Java.

Multithreading is the ability of a Java program to execute multiple threads concurrently, allowing for parallel task execution. It enables efficient utilization of system resources and improves overall program performance. However, managing multiple threads requires synchronization and coordination to avoid issues such as race conditions and deadlocks.

2. What are the differences between method overriding and method overloading?

Method overriding occurs when a subclass defines a method with the same name and signature as an inherited method from its superclass. The overriding method provides a different implementation, replacing the behavior of the superclass method for objects of the subclass. Method overloading, on the other hand, involves defining multiple methods with the same name but different parameters within a class. Overloaded methods enable flexibility by allowing different ways to invoke the same method based on the number and types of arguments passed.

3. Explain the concept of generics in Java.

Generics in Java allow classes and methods to be parameterized by type, providing compile-time type safety. Using generics enables the creation of reusable code independent of specific types, enhancing code readability and maintainability. Generics, such as ArrayList and HashMap, are commonly used with collections to enforce type constraints and enable the compiler to detect type mismatches at compile time.

Tip: When dealing with generics, it is important to specify the appropriate type parameters to ensure type safety and prevent runtime errors.

4. Describe the concept of exception handling in Java.

Exception handling in Java allows programmers to handle and recover from exceptional conditions or errors that may occur during program execution. It involves the use of try-catch blocks to catch and handle exceptions. The catch block contains code to handle specific types of exceptions, providing an alternative course of action when an exception occurs. Additionally, the final block ensures that certain code is executed regardless of whether an exception is thrown.

5. What are the advantages and disadvantages of using an abstract class in Java?

An abstract class in Java serves as a blueprint from which other classes can inherit. It provides a common interface and defines methods and variables that subclasses can implement or override. The advantages of using an abstract class include promoting code reusability, enforcing a consistent structure across related classes, and allowing for future extension through subclassing. However, one disadvantage is that Java does not allow multiple inheritance, so a class can only inherit from one abstract class.

By familiarizing themselves with these advanced Java coding interview questions and understanding the underlying concepts, aspiring Java developers can enhance their problem-solving skills and demonstrate their proficiency in advanced Java programming.

Java Programming Interview Questions

When preparing for a Java programming interview, it’s important to have a solid understanding of the key concepts and techniques that are commonly tested. This section focuses on specific areas of Java programming that you should be prepared to discuss and provides examples of interview questions related to these topics.

Object-Oriented Programming

Object-oriented programming (OOP) is a fundamental aspect of Java programming. Interviewers often ask questions to assess your understanding of OOP principles and how they are implemented in Java. Here are some common interview questions related to OOP:

  • Explain the concept of inheritance and how it is used in Java.
  • What are abstract classes and interfaces, and what is their difference?
  • How does polymorphism work in Java? Provide an example.

Exception Handling

Exception handling is an essential part of Java programming. During an interview, you may be asked how to handle exceptions effectively. Here are a few examples of interview questions related to exception handling:

  • Explain the difference between checked and unchecked exceptions in Java.
  • What is the purpose of the try-catch-finally block? Provide an example.
  • How can you create your custom exceptions in Java?

Multithreading

Understanding multithreading is crucial for developing efficient and responsive Java applications. Interviewers may ask questions about multithreading to assess your knowledge in this area. Here are some common interview questions about multithreading:

  • Explain the difference between a thread and a process.
  • How can you create a new thread in Java? Provide an example.
  • What are the advantages and disadvantages of using multithreading in Java?

By familiarizing yourself with these Java programming interview questions, you can feel more confident and prepared for your next interview. Remember to practice answering these questions and be ready to explain your thought process and demonstrate your problem-solving skills.

problem solving interview questions for java

“Having a strong understanding of object-oriented programming, exception handling, and multithreading in Java is crucial for success in coding interviews.”

Tricky Java Coding Interview Questions

In a Java coding interview, candidates often encounter tricky questions that test their problem-solving skills and critical thinking ability. These questions go beyond the basics and require a deep understanding of Java concepts. To help you prepare for these challenging questions, we have highlighted some examples below and insights on how to approach them.

Question 1: Palindrome Check

Determine whether a given string is a palindrome or not. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward.

Example: Input: “racecar” Output: true Input: “hello” Output: false

To solve this question, you can use two pointers, one starting from the beginning of the string and the other from the end. Compare the characters at each position until the pointers meet. If all the characters match, the string is a palindrome.

Question 2: Find the Missing Number

Given an array of integers from 1 to n with one missing number, find the missing number.

Example: Input: [1, 2, 4, 5, 6] Output: 3

To solve this question, you can calculate the expected sum of all the numbers from 1 to n using the formula (n * (n + 1)) / 2. Then, subtract the sum of the given array from the expected sum to find the missing number.

Question 3: Reverse Linked List

Reverse a singly linked list.

Example: Input: 1 -> 2 -> 3 -> 4 -> 5 Output: 5 -> 4 -> 3 -> 2 -> 1

You can use three-pointers to reverse the links between the nodes to solve this question. Traverse through the linked list and update the next pointers accordingly until you reach the end of the list.

These are just a few examples of tricky Java coding interview questions. By practicing and understanding the underlying concepts, you can improve your problem-solving skills and approach these questions with confidence.

Best Java Coding Interview Questions

Are you preparing for a Java coding interview? This section has curated a list of the best questions for you. These questions cover a wide range of concepts and difficulty levels, ensuring you comprehensively understand Java coding requirements.

Check out the following questions to improve your interview preparation:

  • Question 1: Explain the difference between StringBuffer and StringBuilder. Answer: StringBuffer and StringBuilder are both used to manipulate strings in Java. However, there is a significant difference between them. StringBuffer is synchronized and thread-safe, while StringBuilder is not synchronized but faster. It is important to understand when to use each one based on your requirements.
  • Question 2: What is the difference between a deep and shallow copy? Answer: In Java, a deep copy creates a completely independent copy of an object, including all its nested objects. On the other hand, a shallow copy creates a new object that references the same nested objects as the original object. Understanding the differences between these two copy types is crucial for avoiding unexpected behavior in your code.
  • Question 3: How does Java handle memory management? Explain the concept of garbage collection. Answer: Java uses automatic memory management through a process called garbage collection. Garbage collection identifies and frees up memory that the program no longer uses. This automated memory management relieves developers from manual memory allocation and deallocation, making Java a memory-friendly language.

Mastering these Java coding interview questions will enhance your technical skills and boost your confidence during interviews. In the next section, we will examine some more intriguing questions.

Java Interview Questions for Experienced Developers

Experienced Java developers stand out from the crowd with their depth of knowledge and practical experience. When it comes to interviews, these professionals often face different questions that delve deeper into their expertise. This section is designed to address those specific questions and provide valuable insights for experienced developers.

Here, we will explore advanced concepts and scenarios experienced Java developers will likely encounter during interviews. By understanding and preparing for these questions, you can showcase your proficiency in design patterns, performance optimization, architectural principles, and more.

Sample Questions for Experienced Java Developers

  • How would you optimize the performance of a Java application?
  • Can you explain the differences between checked and unchecked exceptions?
  • Discuss the advantages and disadvantages of using multiple inheritance in Java.
  • Explain the purpose and usage of the Java Volatile keyword.
  • Describe the principles of the Model-View-Controller (MVC) architectural pattern and its implementation in Java.
Experienced Java developers are expected to have a deep understanding of the programming language and its intricacies. Interviewers may ask questions that require practical knowledge, problem-solving skills, and the ability to make architectural decisions.

To further assist you in your preparations, here is a sample table comparing the skills and knowledge required for entry-level Java interviews versus experienced Java interviews:

Remember, the depth of your answers and practical examples of projects you’ve worked on will be crucial in impressing interviewers. Showcase your experience, problem-solving abilities, and the value you can bring as an experienced Java developer.

Top Java Coding Interview Questions

Java coding interview questions are an essential part of the interview process for aspiring Java developers. In this section, we will discuss the top Java coding interview questions that hiring managers frequently ask. By understanding and preparing for these questions, candidates can increase their chances of success in Java coding interviews.

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

2. Explain the concept of object-oriented programming (OOP) and its main principles.

3. What is the difference between equals() and == in Java?

4. Explain the concept of multithreading in Java and how it works.

5. What is the purpose of the “final” keyword in Java?

6. What are checked and unchecked exceptions in Java?

7. Explain the concept of inheritance in Java and how it is implemented.

8. What is the role of the “static” keyword in Java?

“In Java, static keyword is used to create variables and methods that belong to the class, rather than instances of the class. Static members can be accessed directly using the class name, without creating an object. This can be useful for utility methods or variables that need to be shared across all instances of a class.”

9. What is method overloading in Java?

10. Explain the concept of exception handling in Java and how it helps write robust code.

To summarize, being well-prepared for Java coding interviews can significantly improve your chances of landing a job as a Java developer. By familiarizing yourself with these top Java coding interview questions and practicing your problem-solving skills, you can confidently tackle any coding challenge that comes your way.

Comparison between ArrayList and LinkedList in Java

Mastering Java coding interview questions is essential for Java developers looking to excel in their interviews. These questions not only assess a candidate’s technical knowledge but also their problem-solving and critical-thinking skills. By thoroughly studying and practicing these questions, candidates can enhance their understanding of fundamental Java concepts and confidently tackle interview challenges.

Preparing for Java coding interviews involves a combination of theoretical knowledge and practical application. It is important to have a strong understanding of core Java principles and advanced Java concepts. By familiarizing themselves with various Java programming topics, candidates can demonstrate their versatility and ability to adapt to different coding scenarios.

Furthermore, becoming well-versed in Java coding interview questions can significantly boost a candidate’s confidence during the interview process. By knowing how to approach and solve different coding problems, candidates can effectively showcase their technical skills and demonstrate their value to potential employers.

What are Java coding interview questions?

Java coding interview questions assess a candidate’s knowledge and proficiency in Java programming. They cover various aspects of Java, including core concepts, object-oriented programming, data structures, algorithms, and more.

Why are Java coding interview questions important?

Java coding interview questions are important because they help hiring managers evaluate a candidate’s technical skills and problem-solving abilities. Interviewers can assess a candidate’s understanding of Java fundamentals, coding practices, and ability to apply Java concepts to real-world scenarios by asking specific Java coding questions.

What are some common Java coding interview questions?

Common Java coding interview questions include topics such as Java basics (data types, loops, conditionals), object-oriented programming (inheritance, polymorphism), Java collections (ArrayList, HashMap), exception handling, multithreading, and more.

What are core Java interview questions?

Core Java interview questions focus on the fundamental concepts of the Java programming language. They assess a candidate’s knowledge of Java syntax, data types, operators, control flow, classes and objects, inheritance, interfaces, and basic Java libraries.

What are advanced Java coding interview questions?

Advanced Java coding interview questions are designed to evaluate a candidate’s in-depth understanding of complex Java concepts and advanced programming techniques. These questions often cover advanced topics such as multithreading, Java Generics, Java streams, concurrency, design patterns, and performance optimization.

What are Java programming interview questions?

Java programming interview questions focus on assessing a candidate’s ability to apply Java programming concepts to solve specific problems. These questions cover object-oriented programming, exception handling, data structures, algorithms, database connectivity, and Java frameworks.

What are some tricky Java coding interview questions?

Tricky Java coding interview questions are designed to challenge a candidate’s problem-solving abilities and critical thinking skills. They often involve complex scenarios, edge cases, or unexpected behavior of Java language features. Candidates must analyze the problem, consider different approaches, and provide the most appropriate solution.

What are the best Java coding interview questions?

The best Java coding interview questions cover a wide range of Java concepts and difficulty levels. These questions effectively evaluate a candidate’s understanding of core Java principles, ability to write clean and efficient code, and problem-solving skills. They provide a comprehensive assessment of a candidate’s Java programming proficiency.

What are Java interview questions for experienced developers?

Java interview questions for experienced developers are specifically tailored to evaluate their advanced knowledge and practical experience with Java programming. These questions may delve into advanced Java topics, design patterns, database integration, performance tuning, debugging techniques, and frameworks commonly used in enterprise-level applications.

What are the top Java coding interview questions?

The top Java coding interview questions are hiring managers’ most frequently asked questions. These questions cover a variety of Java concepts and are specifically designed to assess a candidate’s problem-solving skills, coding techniques, familiarity with Java libraries/frameworks, and ability to write efficient and maintainable code.

AI Proof Your Career

Logo 1

Secure Your Lifetime 20% Discount for Project-Based Learning. Use code LIFETIME20

Learn Java and Programming through articles, code examples, and tutorials for developers of all levels.

  • online courses
  • certification
  • free resources

Top 75 Programming Interview Questions Answers to Crack Any Coding Job Interview

Top 50 coding interview questions for programmers (2023), 1. array-based programming interview questions.

Array based Programming Interview Questions Answers

I say "hey guys..." in much the same way a southerner says "ya'll", it's just a plural for a group. Stop turning everything into a problem.

Yeah, about time, I change my style and start saying "Hello all", thanks a lot.

Sorry, I didn't mean that. It's just my casual way to start the article. I very much appreciate woman in tech and female software engineer. About time, I change my style to say "Hello All" instead of of "Hello Guys". Thanks

Hey feminist, it is just a word. Really you are going to get offended and discount everything that the page says because of one word? A real strong woman would move past it and realize the interview questions included within are actually quite good and detailed and probably will prepare you quite well for a job interview. Instead you are so concerned about the word "guys" at the top. Did you ever notice how actual guys don't spend time worrying about trivial things and just focus on getting the job done. Try that instead.

All the lady engineers who get help from male engineers should remember to give back. Time and again, my experience with female engineers at conferences has been very poor. There is no sharing of knowledge. It cannot be one way street in the name of equality. Two, please respect the author who works for the whole community, rather than nit-picking over political correctness. Three, have courage to post a comment like this with your own signature, not anonymously. :-)

Oh please, if you respected women in the industry, you wouldn't be so critical of them. I agree with the poster. The terminology should be more inclusive. It's a matter of respect.

omg, you fight each other just for "hello guys" words ?

Very useful..Thanks..!!

Good work..

This is a great list of problems, but I believe readers should look elsewhere for correct solutions. I haven't opened all of them, but some of them (e.g. "remove duplicate chars from string", "find square root of a number") have some pretty bizarre solutions.

for square root I can understand but remove duplicate character from string seems straightforward, no?

Maybe you should "hello world" instead!

Wow... I'm about 10 years into the developer job and not able to solve many of these question. Think I should quit my job :(

You are not alone it happened to everybody. You just need a bit of practice and you will be fine.

Thanks - but what to practice is the key question :)

I just came here to read the comments. You guys have become popular, cheers !

Feel free to comment, ask questions if you have any doubt.

Welcome to Java! Easy Max Score: 3 Success Rate: 97.05%

Java stdin and stdout i easy java (basic) max score: 5 success rate: 96.88%, java if-else easy java (basic) max score: 10 success rate: 91.34%, java stdin and stdout ii easy java (basic) max score: 10 success rate: 92.64%, java output formatting easy java (basic) max score: 10 success rate: 96.54%, java loops i easy java (basic) max score: 10 success rate: 97.67%, java loops ii easy java (basic) max score: 10 success rate: 97.31%, java datatypes easy java (basic) max score: 10 success rate: 93.66%, java end-of-file easy java (basic) max score: 10 success rate: 97.91%, java static initializer block easy java (basic) max score: 10 success rate: 96.13%, cookie support is required to access hackerrank.

Seems like cookies are disabled on this browser, please enable them to open this website

Top 20 Problem Solving Interview Questions (Example Answers Included)

Mike Simpson 0 Comments

problem solving interview questions for java

By Mike Simpson

When candidates prepare for interviews, they usually focus on highlighting their leadership, communication, teamwork, and similar crucial soft skills . However, not everyone gets ready for problem-solving interview questions. And that can be a big mistake.

Problem-solving is relevant to nearly any job on the planet. Yes, it’s more prevalent in certain industries, but it’s helpful almost everywhere.

Regardless of the role you want to land, you may be asked to provide problem-solving examples or describe how you would deal with specific situations. That’s why being ready to showcase your problem-solving skills is so vital.

If you aren’t sure who to tackle problem-solving questions, don’t worry, we have your back. Come with us as we explore this exciting part of the interview process, as well as some problem-solving interview questions and example answers.

What Is Problem-Solving?

When you’re trying to land a position, there’s a good chance you’ll face some problem-solving interview questions. But what exactly is problem-solving? And why is it so important to hiring managers?

Well, the good folks at Merriam-Webster define problem-solving as “the process or act of finding a solution to a problem.” While that may seem like common sense, there’s a critical part to that definition that should catch your eye.

What part is that? The word “process.”

In the end, problem-solving is an activity. It’s your ability to take appropriate steps to find answers, determine how to proceed, or otherwise overcome the challenge.

Being great at it usually means having a range of helpful problem-solving skills and traits. Research, diligence, patience, attention-to-detail , collaboration… they can all play a role. So can analytical thinking , creativity, and open-mindedness.

But why do hiring managers worry about your problem-solving skills? Well, mainly, because every job comes with its fair share of problems.

While problem-solving is relevant to scientific, technical, legal, medical, and a whole slew of other careers. It helps you overcome challenges and deal with the unexpected. It plays a role in troubleshooting and innovation. That’s why it matters to hiring managers.

How to Answer Problem-Solving Interview Questions

Okay, before we get to our examples, let’s take a quick second to talk about strategy. Knowing how to answer problem-solving interview questions is crucial. Why? Because the hiring manager might ask you something that you don’t anticipate.

Problem-solving interview questions are all about seeing how you think. As a result, they can be a bit… unconventional.

These aren’t your run-of-the-mill job interview questions . Instead, they are tricky behavioral interview questions . After all, the goal is to find out how you approach problem-solving, so most are going to feature scenarios, brainteasers, or something similar.

So, having a great strategy means knowing how to deal with behavioral questions. Luckily, there are a couple of tools that can help.

First, when it comes to the classic approach to behavioral interview questions, look no further than the STAR Method . With the STAR method, you learn how to turn your answers into captivating stories. This makes your responses tons more engaging, ensuring you keep the hiring manager’s attention from beginning to end.

Now, should you stop with the STAR Method? Of course not. If you want to take your answers to the next level, spend some time with the Tailoring Method , too.

With the Tailoring Method, it’s all about relevance. So, if you get a chance to choose an example that demonstrates your problem-solving skills, this is really the way to go.

We also wanted to let you know that we created an amazing free cheat sheet that will give you word-for-word answers for some of the toughest interview questions you are going to face in your upcoming interview. After all, hiring managers will often ask you more generalized interview questions!

Click below to get your free PDF now:

Get Our Job Interview Questions & Answers Cheat Sheet!

FREE BONUS PDF CHEAT SHEET: Get our " Job Interview Questions & Answers PDF Cheat Sheet " that gives you " word-word sample answers to the most common job interview questions you'll face at your next interview .

CLICK HERE TO GET THE JOB INTERVIEW QUESTIONS CHEAT SHEET

Top 3 Problem-Solving-Based Interview Questions

Alright, here is what you’ve been waiting for: the problem-solving questions and sample answers.

While many questions in this category are job-specific, these tend to apply to nearly any job. That means there’s a good chance you’ll come across them at some point in your career, making them a great starting point when you’re practicing for an interview.

So, let’s dive in, shall we? Here’s a look at the top three problem-solving interview questions and example responses.

1. Can you tell me about a time when you had to solve a challenging problem?

In the land of problem-solving questions, this one might be your best-case scenario. It lets you choose your own problem-solving examples to highlight, putting you in complete control.

When you choose an example, go with one that is relevant to what you’ll face in the role. The closer the match, the better the answer is in the eyes of the hiring manager.

EXAMPLE ANSWER:

“While working as a mobile telecom support specialist for a large organization, we had to transition our MDM service from one vendor to another within 45 days. This personally physically handling 500 devices within the agency. Devices had to be gathered from the headquarters and satellite offices, which were located all across the state, something that was challenging even without the tight deadline. I approached the situation by identifying the location assignment of all personnel within the organization, enabling me to estimate transit times for receiving the devices. Next, I timed out how many devices I could personally update in a day. Together, this allowed me to create a general timeline. After that, I coordinated with each location, both expressing the urgency of adhering to deadlines and scheduling bulk shipping options. While there were occasional bouts of resistance, I worked with location leaders to calm concerns and facilitate action. While performing all of the updates was daunting, my approach to organizing the event made it a success. Ultimately, the entire transition was finished five days before the deadline, exceeding the expectations of many.”

2. Describe a time where you made a mistake. What did you do to fix it?

While this might not look like it’s based on problem-solving on the surface, it actually is. When you make a mistake, it creates a challenge, one you have to work your way through. At a minimum, it’s an opportunity to highlight problem-solving skills, even if you don’t address the topic directly.

When you choose an example, you want to go with a situation where the end was positive. However, the issue still has to be significant, causing something negative to happen in the moment that you, ideally, overcame.

“When I first began in a supervisory role, I had trouble setting down my individual contributor hat. I tried to keep up with my past duties while also taking on the responsibilities of my new role. As a result, I began rushing and introduced an error into the code of the software my team was updating. The error led to a memory leak. We became aware of the issue when the performance was hindered, though we didn’t immediately know the cause. I dove back into the code, reviewing recent changes, and, ultimately, determined the issue was a mistake on my end. When I made that discovery, I took several steps. First, I let my team know that the error was mine and let them know its nature. Second, I worked with my team to correct the issue, resolving the memory leak. Finally, I took this as a lesson about delegation. I began assigning work to my team more effectively, a move that allowed me to excel as a manager and help them thrive as contributors. It was a crucial learning moment, one that I have valued every day since.”

3. If you identify a potential risk in a project, what steps do you take to prevent it?

Yes, this is also a problem-solving question. The difference is, with this one, it’s not about fixing an issue; it’s about stopping it from happening. Still, you use problem-solving skills along the way, so it falls in this question category.

If you can, use an example of a moment when you mitigated risk in the past. If you haven’t had that opportunity, approach it theoretically, discussing the steps you would take to prevent an issue from developing.

“If I identify a potential risk in a project, my first step is to assess the various factors that could lead to a poor outcome. Prevention requires analysis. Ensuring I fully understand what can trigger the undesired event creates the right foundation, allowing me to figure out how to reduce the likelihood of those events occurring. Once I have the right level of understanding, I come up with a mitigation plan. Exactly what this includes varies depending on the nature of the issue, though it usually involves various steps and checks designed to monitor the project as it progresses to spot paths that may make the problem more likely to happen. I find this approach effective as it combines knowledge and ongoing vigilance. That way, if the project begins to head into risky territory, I can correct its trajectory.”

17 More Problem-Solving-Based Interview Questions

In the world of problem-solving questions, some apply to a wide range of jobs, while others are more niche. For example, customer service reps and IT helpdesk professionals both encounter challenges, but not usually the same kind.

As a result, some of the questions in this list may be more relevant to certain careers than others. However, they all give you insights into what this kind of question looks like, making them worth reviewing.

Here are 17 more problem-solving interview questions you might face off against during your job search:

  • How would you describe your problem-solving skills?
  • Can you tell me about a time when you had to use creativity to deal with an obstacle?
  • Describe a time when you discovered an unmet customer need while assisting a customer and found a way to meet it.
  • If you were faced with an upset customer, how would you diffuse the situation?
  • Tell me about a time when you had to troubleshoot a complex issue.
  • Imagine you were overseeing a project and needed a particular item. You have two choices of vendors: one that can deliver on time but would be over budget, and one that’s under budget but would deliver one week later than you need it. How do you figure out which approach to use?
  • Your manager wants to upgrade a tool you regularly use for your job and wants your recommendation. How do you formulate one?
  • A supplier has said that an item you need for a project isn’t going to be delivered as scheduled, something that would cause your project to fall behind schedule. What do you do to try and keep the timeline on target?
  • Can you share an example of a moment where you encountered a unique problem you and your colleagues had never seen before? How did you figure out what to do?
  • Imagine you were scheduled to give a presentation with a colleague, and your colleague called in sick right before it was set to begin. What would you do?
  • If you are given two urgent tasks from different members of the leadership team, both with the same tight deadline, how do you choose which to tackle first?
  • Tell me about a time you and a colleague didn’t see eye-to-eye. How did you decide what to do?
  • Describe your troubleshooting process.
  • Tell me about a time where there was a problem that you weren’t able to solve. What happened?
  • In your opening, what skills or traits make a person an exceptional problem-solver?
  • When you face a problem that requires action, do you usually jump in or take a moment to carefully assess the situation?
  • When you encounter a new problem you’ve never seen before, what is the first step that you take?

Putting It All Together

At this point, you should have a solid idea of how to approach problem-solving interview questions. Use the tips above to your advantage. That way, you can thrive during your next interview.

FREE : Job Interview Questions & Answers PDF Cheat Sheet!

Download our " Job Interview Questions & Answers PDF Cheat Sheet " that gives you word-for-word sample answers to some of the most common interview questions including:

  • What Is Your Greatest Weakness?
  • What Is Your Greatest Strength?
  • Tell Me About Yourself
  • Why Should We Hire You?

Click Here To Get The Job Interview Questions & Answers Cheat Sheet

problem solving interview questions for java

Co-Founder and CEO of TheInterviewGuys.com. Mike is a job interview and career expert and the head writer at TheInterviewGuys.com.

His advice and insights have been shared and featured by publications such as Forbes , Entrepreneur , CNBC and more as well as educational institutions such as the University of Michigan , Penn State , Northeastern and others.

Learn more about The Interview Guys on our About Us page .

About The Author

Mike simpson.

' src=

Co-Founder and CEO of TheInterviewGuys.com. Mike is a job interview and career expert and the head writer at TheInterviewGuys.com. His advice and insights have been shared and featured by publications such as Forbes , Entrepreneur , CNBC and more as well as educational institutions such as the University of Michigan , Penn State , Northeastern and others. Learn more about The Interview Guys on our About Us page .

Copyright © 2024 · TheInterviewguys.com · All Rights Reserved

  • Our Products
  • Case Studies
  • Interview Questions
  • Jobs Articles
  • Members Login

problem solving interview questions for java

Javarevisited

Learn Java, Programming, Spring, Hibernate throw tutorials, examples, and interview questions

Topics and Categories

  • collections
  • multithreading
  • design patterns
  • interview questions
  • data structure
  • Java Certifications
  • jsp-servlet
  • online resources
  • jvm-internals

Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Tuesday, March 26, 2024

  • Top 50 Java Programs from Coding Interviews

Java Programming Interview Questions for 2 to 3 years

  Related Articles:

  • Top 50 String Coding Problems for Interviews
  • Top 50 Tree Coding Problems for Interviews
  • Top 50 Graph Coding Problems for Interviews
  • Top 50 Dynamic Programming Coding Problems for Interviews
  • Top 50 Sorting Coding Problems for Interviews
  • Top 50 Searching Coding Problems for Interviews
  • Top 50 Binary Search Tree Coding Problems for Interviews

Some other important Tutorials:

  • DSA Tutorial
  • System Design Tutorial
  • Software Development Roadmap
  • Roadmap to become a Product Manager
  • Learn SAP interview questions

Track your progress and attempt this list on GfG Practice.

Please Login to comment...

Similar reads.

author

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Create Account / Login

JavaScript Interview Questions

problem solving interview questions for java

Team Glider

problem solving interview questions for java

In this post

  • AI Proctoring (111)
  • AI Recruiting (14)
  • Assessments (26)
  • Diversity Equity & Inclusion (DEI) (15)
  • Glider News & Offers (22)
  • Hiring Processes & Strategies (106)
  • Interview Questions (304)
  • Job Descriptions (258)
  • Product News (6)
  • Staffing Industry News (12)
  • Tech Hiring Guide (234)

Whether hiring for an entry-level web developer position or a web architect, asking the right   JavaScript coding questions   lets you assess the candidate’s depth of knowledge in core JavaScript concepts, problem-solving skills, and understanding of modern JavaScript practices. 

More than identifying which people in your pool of applicants can answer technical questions , these JavaScript interview questions also reveal who among them can apply their knowledge in real-world scenarios.

As you know, hiring the wrong person is tantamount to wasting money and training time. It also hurts productivity and can even demoralize current employees. 

By asking the right JavaScript interview questions from the start, you can select candidates who can bring practical value to your project.

Focusing on the right questions also minimizes bias based on first impressions. Well-designed  JavaScript coding questions   create a fair evaluation process.

JavaScript interview questions for beginners

Positions like junior web developers and content management system administrators often use basic JavaScript to add interactivity to web pages and for content editing. 

Non-technical roles like business analysts may need basic JavaScript to automate data manipulation tasks. Here are some basic JavaScript interview questions  you can ask candidates applying for these roles:

JavaScript basics

  • What is JavaScript?
  • List some features of JavaScript.
  • Who developed JavaScript, and what was its first name?
  • List some of the advantages of JavaScript.
  • List some of the disadvantages of JavaScript.
  • Is JavaScript a case-sensitive language?
  • How do you write a hello world example of JavaScript?
  • How do you use an external JavaScript file?

Functions in JavaScript

  • Define a named function in JavaScript.
  • Name the types of functions.
  • Define an anonymous function.
  • Can an anonymous function be assigned to a variable?
  • In JavaScript, what is an argument object?
  • Define closure.

JavaScript in use

  • What method is used to return the character from a specific index? 

JavaScript objects

  • What is BOM (Browser Object Model)?
  • What is DOM (Document Object Model)? What is the use of the document object?
  • What is the use of the window object?

Differences and comparisons

  • How are JavaScript and Jscript different?
  • How are Java and JavaScript different?

Intermediate JavaScript interview questions

Are you hiring a front-end developer, a junior data analyst, a web app QA tester, or an e-commerce specialist? 

The JavaScript interview questions and coding exercises below are suitable for assessing candidates applying for these roles. 

They progress from basic JavaScript syntax and functions through data handling and operations to more advanced topics and interactions with the web environment. 

JavaScript basics and syntax

  • How do you write a comment in JavaScript?
  • How do you create a function in JavaScript?
  • What is the actual name of JavaScript?

JavaScript data handling

  • What are the different data types present in JavaScript?
  • How are == and === different?
  • What does the isNaN() function do?
  • What is the output of 10+20+ “30” in JavaScript?
  • What is the production of “10” +20+30 in JavaScript?
  • What is the difference between an undefined value and a null value?

JavaScript objects and arrays

  • How do you create objects in JavaScript?
  • Describe how to create an array.

Web storage and events

  • Can you explain which location cookies are typically stored on the hard disk?

Intermediate JavaScript concepts

  • What is the use of the history object?
  • How do you write HTML code dynamically using JavaScript?
  • How do you write regular text code using JavaScript dynamically?
  • What’s the difference between Client-side JavaScript and Server-side JavaScript?
  • What’s the difference between event.preventDefault() and event.stopPropagation() methods in JavaScript?
  • How can you determine if an event’s default behavior was prevented using an event in JavaScript?preventDefault() within a specific element? 
  • Describe how to set the cursor to wait.

Advanced JavaScript Interview Questions

To test a candidate’s grasp of advanced JavaScript concepts, you need to cover

essential to complex aspects — data handling, user interaction, state management, and performance. 

The JavaScript interview questions below suit higher roles, including software engineers specializing in complex web apps and back-end systems, full-stack developers, web architects, and web-based game developers. 

You can also use them when interviewing data scientist applicants who need to know how to use JavaScript to deal with large datasets.

JavaScript fundamentals

  • Are Java and JavaScript the same?
  • What is negative infinity?
  • What is this keyword in JavaScript?
  • What are the falsy values in JavaScript, and how can we check if a value is falsy?
  • What does hoisting mean in JavaScript?
  • What is JavaScript’s strict mode, and how does it affect how your code runs?

JavaScript programming techniques

  • How are exceptions in JavaScript handled?
  • What is the requirement of debugging in JavaScript?
  • What is the use of the debugger keyword in JavaScript?

Form and user interaction

  • How do you submit a form using JavaScript by clicking a link?
  • How do you validate a form/an email in JavaScript?
  • How do you use JavaScript to detect the client machine’s OS?
  • How do you change the background color of an HTML document using JavaScript?

Pop-ups and UI feedback

  • Can you explain the different ways to create user interactions resembling JavaScript pop-up boxes?

Web state management

  • How are the Session state and View state different? 

Performance considerations

  • Is JavaScript faster than ASP script?

JavaScript objects and data types

  • What are some of the standard functionalities of Math objects in JavaScript?
  • What is the use of a Date object in JavaScript?
  • What is the use of a Number object in JavaScript?
  • What are some of the standard functionalities of a Boolean object in JavaScript?
  • What is the use of a TypedArray object in JavaScript?
  • What is the use of a Set object in JavaScript?
  • What is the use of a WeakSet object in JavaScript?
  • What is the use of a Map object in JavaScript?
  • What are some of the standard functionalities of a WeakMap object in JavaScript?

Because JavaScript is constantly evolving, you need to regularly update this list of JavaScript coding questions and JavaScript interview questions to reflect the latest standards. 

Making your questions relevant and up-to-date lets you test a candidate’s knowledge of the current best practices and ultimately helps you hire someone who can add value to your projects.

Accelerate the hiring of top talent

Make talent quality your leading analytic with skills-based hiring solution.

problem solving interview questions for java

QA & Testing​ – Top Job Roles and Skills

problem solving interview questions for java

Data Science and Analytics – Top Job Roles and Skills

problem solving interview questions for java

Enterprise Software – Top Jobs and Skills

Download Interview guide PDF

Javascript interview questions, download pdf.

JavaScript , created by Brendan Eich in 1995, is one of the most widely used web development languages. It was designed to build dynamic web pages at first. A script is a JS program that may be added to the HTML of any web page. When the page loads, these scripts execute automatically.

A language that was originally designed to build dynamic web pages may now be run on the server and on almost any device that has the JavaScript Engine installed.

After HTML and CSS, JavaScript is the third biggest web technology. JavaScript is a scripting language that may be used to construct online and mobile apps, web servers, games, and more. JavaScript is an object-oriented programming language that is used to generate websites and applications. It was created with the intention of being used in a browser. Even today, the server-side version of JavaScript known as Node.js may be used to create online and mobile apps, real-time applications, online streaming applications, and videogames. Javascript frameworks , often known as inbuilt libraries, may be used to construct desktop and mobile programs. Developers may save a lot of time on monotonous programming jobs by using these code libraries, allowing them to focus on the production work of development.

The InterviewBit team has compiled a thorough collection of top Javascript Interview Questions and Answers to assist you in acing your interview and landing your desired job as a Javascript Developer. 

JavaScript Interview Questions for Freshers

1. what are the different data types present in javascript.

To know the type of a JavaScript variable, we can use the typeof operator.

1. Primitive types

String - It represents a series of characters and is written with quotes. A string can be represented using a single or a double quote.

  • Number - It represents a number and can be written with or without decimals.
  • BigInt - This data type is used to store numbers which are above the limitation of the Number data type. It can store large integers and is represented by adding “n” to an integer literal.
  • Boolean - It represents a logical entity and can have only two values : true or false. Booleans are generally used for conditional testing.
  • Undefined - When a variable is declared but not assigned, it has the value of undefined and it’s type is also undefined.
  • Null - It represents a non-existent or a invalid value.
  • Symbol - It is a new data type introduced in the ES6 version of javascript. It is used to store an anonymous and unique value.
  • typeof of primitive types :

2. Non-primitive types

  • Primitive data types can store only a single value. To store multiple and complex values, non-primitive data types are used.
  • Object - Used to store collection of data.
Note- It is important to remember that any data type that is not a primitive data type, is of Object type in javascript.

2. Explain Hoisting in javascript.

Hoisting is the default behaviour of javascript where all the variable and function declarations are moved on top.

problem solving interview questions for java

This means that irrespective of where the variables and functions are declared, they are moved on top of the scope. The scope can be both local and global. Example 1:

doSomething(); // Outputs 33 since the local variable “x” is hoisted inside the local scope

Note - Variable initializations are not hoisted, only variable declarations are hoisted:
Note - To avoid hoisting, you can run javascript in strict mode by using “use strict” on top of the code:

3. Why do we use the word “debugger” in javascript?

The debugger for the browser must be activated in order to debug the code. Built-in debuggers may be switched on and off, requiring the user to report faults. The remaining section of the code should stop execution before moving on to the next line while debugging.

4. Difference between “ == “ and “ === “ operators.

Both are comparison operators. The difference between both the operators is that “==” is used to compare values whereas, “ === “ is used to compare both values and types.

5. Difference between var and let keyword in javascript.

Some differences are  

  • From the very beginning, the 'var' keyword was used in JavaScript programming whereas the keyword 'let' was just added in 2015.
  • The keyword 'Var' has a function scope. Anywhere in the function, the variable specified using var is accessible but in ‘let’ the scope of a variable declared with the 'let' keyword is limited to the block in which it is declared. Let's start with a Block Scope.
  • In ECMAScript 2015, let and const are hoisted but not initialized. Referencing the variable in the block before the variable declaration results in a ReferenceError because the variable is in a "temporal dead zone" from the start of the block until the declaration is processed.
  • Software Dev
  • Data Science

6. Explain Implicit Type Coercion in javascript.

Implicit type coercion in javascript is the automatic conversion of value from one data type to another. It takes place when the operands of an expression are of different data types.

  • String coercion

String coercion takes place while using the ‘ + ‘ operator. When a number is added to a string, the number type is always converted to the string type.

Note - ‘ + ‘ operator when used to add two numbers, outputs a number. The same ‘ + ‘ operator when used to add two strings, outputs the concatenated string:

Let’s understand both the examples where we have added a number to a string,

When JavaScript sees that the operands of the expression x + y are of different types ( one being a number type and the other being a string type ), it converts the number type to the string type and then performs the operation. Since after conversion, both the variables are of string type, the ‘ + ‘ operator outputs the concatenated string “33” in the first example and “24Hello” in the second example.

Note - Type coercion also takes place when using the ‘ - ‘ operator, but the difference while using ‘ - ‘ operator is that, a string is converted to a number and then subtraction takes place.
  • Boolean Coercion

Boolean coercion takes place when using logical operators, ternary operators, if statements, and loop checks. To understand boolean coercion in if statements and operators, we need to understand truthy and falsy values. Truthy values are those which will be converted (coerced) to true . Falsy values are those which will be converted to false . All values except false, 0, 0n, -0, “”, null, undefined, and NaN are truthy values.

If statements:

  • Logical operators:

Logical operators in javascript, unlike operators in other programming languages, do not return true or false. They always return one of the operands. OR ( | | ) operator - If the first value is truthy, then the first value is returned. Otherwise, always the second value gets returned. AND ( && ) operator - If both the values are truthy, always the second value is returned. If the first value is falsy then the first value is returned or if the second value is falsy then the second value is returned. Example:

  • Equality Coercion

Equality coercion takes place when using ‘ == ‘ operator. As we have stated before The ‘ == ‘ operator compares values and not types. While the above statement is a simple way to explain == operator, it’s not completely true The reality is that while using the ‘==’ operator, coercion takes place. The ‘==’ operator, converts both the operands to the same type and then compares them. Example:

Coercion does not take place when using the ‘===’ operator. Both operands are not converted to the same type in the case of ‘===’ operator.

7. Is javascript a statically typed or a dynamically typed language?

JavaScript is a dynamically typed language. In a dynamically typed language, the type of a variable is checked during run-time in contrast to a statically typed language, where the type of a variable is checked during compile-time.

problem solving interview questions for java

Since javascript is a loosely(dynamically) typed language, variables in JS are not associated with any type. A variable can hold the value of any data type.

For example, a variable that is assigned a number type can be converted to a string type:

8. What is NaN property in JavaScript?

NaN property represents the “Not-a-Number” value. It indicates a value that is not a legal number.

typeof of NaN will return a Number .

To check if a value is NaN, we use the isNaN() function,

Note- isNaN() function converts the given value to a Number type, and then equates to NaN.

9. Explain passed by value and passed by reference.

In JavaScript, primitive data types are passed by value and non-primitive data types are passed by reference. For understanding passed by value and passed by reference, we need to understand what happens when we create a variable and assign a value to it,

In the above example, we created a variable x and assigned it a value of “2”. In the background, the “=” (assign operator) allocates some space in the memory, stores the value “2” and returns the location of the allocated memory space. Therefore, the variable x in the above code points to the location of the memory space instead of pointing to the value 2 directly.

Assign operator behaves differently when dealing with primitive and non-primitive data types, Assign operator dealing with primitive types:

problem solving interview questions for java

In the above example, the assign operator knows that the value assigned to y is a primitive type (number type in this case), so when the second line code executes, where the value of y is assigned to z, the assign operator takes the value of y (234) and allocates a new space in the memory and returns the address. Therefore, variable z is not pointing to the location of variable y, instead, it is pointing to a new location in the memory.

From the above example, we can see that primitive data types when passed to another variable, are passed by value. Instead of just assigning the same address to another variable, the value is passed and new space of memory is created. Assign operator dealing with non-primitive types:

problem solving interview questions for java

In the above example, the assign operator directly passes the location of the variable obj to the variable obj2. In other words, the reference of the variable obj is passed to the variable obj2.

From the above example, we can see that while passing non-primitive data types, the assigned operator directly passes the address (reference). Therefore, non-primitive data types are always passed by reference.

10. What is an Immediately Invoked Function in JavaScript?

An Immediately Invoked Function ( known as IIFE and pronounced as IIFY) is a function that runs as soon as it is defined.

Syntax of IIFE :

To understand IIFE, we need to understand the two sets of parentheses that are added while creating an IIFE : The first set of parenthesis:

While executing javascript code, whenever the compiler sees the word “function”, it assumes that we are declaring a function in the code. Therefore, if we do not use the first set of parentheses, the compiler throws an error because it thinks we are declaring a function, and by the syntax of declaring a function, a function should always have a name.

To remove this error, we add the first set of parenthesis that tells the compiler that the function is not a function declaration, instead, it’s a function expression. The second set of parenthesis:

From the definition of an IIFE, we know that our code should run as soon as it is defined. A function runs only when it is invoked. If we do not invoke the function, the function declaration is returned:

Therefore to invoke the function, we use the second set of parenthesis.

11. What do you mean by strict mode in javascript and characteristics of javascript strict-mode?

In ECMAScript 5, a new feature called JavaScript Strict Mode allows you to write a code or a function in a "strict" operational environment. In most cases, this language is 'not particularly severe' when it comes to throwing errors. In 'Strict mode,' however, all forms of errors, including silent errors, will be thrown. As a result, debugging becomes a lot simpler.  Thus programmer's chances of making an error are lowered.

Characteristics of strict mode in javascript

  • Duplicate arguments are not allowed by developers.
  • In strict mode, you won't be able to use the JavaScript keyword as a parameter or function name.
  • The 'use strict' keyword is used to define strict mode at the start of the script. Strict mode is supported by all browsers.
  • Engineers will not be allowed to create global variables in 'Strict Mode.

12. Explain Higher Order Functions in javascript.

Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions. Higher-order functions are a result of functions being first-class citizens in javascript.

Examples of higher-order functions:

13. Explain “this” keyword.

The “this” keyword refers to the object that the function is a property of. The value of the “this” keyword will always depend on the object that is invoking the function.\

Confused? Let’s understand the above statements by examples:

What do you think the output of the above code will be?

Note - Observe the line where we are invoking the function.

Check the definition again:

The “this” keyword refers to the object that the function is a property of.

In the above code, the function is a property of which object?

Since the function is invoked in the global context, the function is a property of the global object.

Therefore, the output of the above code will be the global object. Since we ran the above code inside the browser, the global object is the window object.

In the above code, at the time of invocation, the getName function is a property of the object obj , therefore, this keyword will refer to the object obj , and hence the output will be “vivek”.

Can you guess the output here?

The output will be “akshay”.

Although the getName function is declared inside the object obj , at the time of invocation, getName() is a property of obj2 , therefore the “this” keyword will refer to obj2 .

The silly way to understand the “ this” keyword is, whenever the function is invoked, check the object before the dot . The value of this . keyword will always be the object before the dot .

If there is no object before the dot-like in example1, the value of this keyword will be the global object.

Can you guess the output?

The output will be an error.

Although in the code above, this keyword refers to the object obj2 , obj2 does not have the property “address”‘, hence the getAddress function throws an error.

14. What do you mean by Self Invoking Functions?

Without being requested, a self-invoking expression is automatically invoked (initiated). If a function expression is followed by (), it will execute automatically. A function declaration cannot be invoked by itself.

Normally, we declare a function and call it, however, anonymous functions may be used to run a function automatically when it is described and will not be called again. And there is no name for these kinds of functions.

15. Explain call(), apply() and, bind() methods.

  • It’s a predefined method in javascript.
  • This method invokes a method (function) by specifying the owner object.
  • call() method allows an object to use the method (function) of another object.
  • call() accepts arguments:

apply() The apply method is similar to the call() method. The only difference is that, call() method takes arguments separately whereas, apply() method takes arguments as an array.

  • This method returns a new function, where the value of “this” keyword will be bound to the owner object, which is provided as a parameter.
  • Example with arguments:

16. What is the difference between exec () and test () methods in javascript?

  • test () and exec () are RegExp expression methods used in javascript. 
  • We'll use exec () to search a string for a specific pattern, and if it finds it, it'll return the pattern directly; else, it'll return an 'empty' result.
  • We will use a test () to find a string for a specific pattern. It will return the Boolean value 'true' on finding the given text otherwise, it will return 'false'.

17. What is currying in JavaScript?

Currying is an advanced technique to transform a function of arguments n, to n functions of one or fewer arguments.

Example of a curried function:

For Example, if we have a function f(a,b) , then the function after currying, will be transformed to f(a)(b). By using the currying technique, we do not change the functionality of a function, we just change the way it is invoked. Let’s see currying in action:

As one can see in the code above, we have transformed the function multiply(a,b) to a function curriedMultiply , which takes in one parameter at a time.

18. What are some advantages of using External JavaScript?

External JavaScript is the JavaScript Code (script) written in a separate file with the extension.js, and then we link that file inside the <head> or <body> element of the HTML file where the code is to be placed.  

Some advantages of external javascript are

  • It allows web designers and developers to collaborate on HTML and javascript files.
  • We can reuse the code.
  • Code readability is simple in external javascript.

19. Explain Scope and Scope Chain in javascript.

Scope in JS determines the accessibility of variables and functions at various parts of one’s code. In general terms, the scope will let us know at a given part of code, what are variables and functions we can or cannot access. There are three types of scopes in JS:

  • Global Scope
  • Local or Function Scope
  • Block Scope

Global Scope: Variables or functions declared in the global namespace have global scope, which means all the variables and functions having global scope can be accessed from anywhere inside the code.

Function Scope: Any variables or functions declared inside a function have local/function scope, which means that all the variables and functions declared inside a function, can be accessed from within the function and not outside of it.

Block Scope: Block scope is related to the variables declared using let and const. Variables declared with var do not have block scope. Block scope tells us that any variable declared inside a block { }, can be accessed only inside that block and cannot be accessed outside of it.

Scope Chain: JavaScript engine also uses Scope to find variables. Let’s understand that using an example:

As you can see in the code above, if the javascript engine does not find the variable in local scope, it tries to check for the variable in the outer scope. If the variable does not exist in the outer scope, it tries to find the variable in the global scope.

If the variable is not found in the global space as well, a reference error is thrown.

20. Explain Closures in JavaScript.

Closures are an ability of a function to remember the variables and functions that are declared in its outer scope.

Let’s understand closures by example:

Let’s understand the code above, The function randomFunc() gets executed and returns a function when we assign it to a variable:

The returned function is then executed when we invoke initialiseClosure:

The line of code above outputs “Vivian is awesome” and this is possible because of closure.

When the function randomFunc() runs, it seems that the returning function is using the variable obj1 inside it:

Therefore randomFunc(), instead of destroying the value of obj1 after execution, saves the value in the memory for further reference. This is the reason why the returning function is able to use the variable declared in the outer scope even after the function is already executed. This ability of a function to store a variable for further reference even after it is executed is called Closure.

21. Mention some advantages of javascript.

There are many advantages of javascript. Some of them are 

  • Javascript is executed on the client-side as well as server-side also. There are a variety of Frontend Frameworks that you may study and utilize. However, if you want to use JavaScript on the backend, you'll need to learn NodeJS. It is currently the only JavaScript framework that may be used on the backend.
  • Javascript is a simple language to learn.
  • Web pages now have more functionality because of Javascript.
  • To the end-user, Javascript is quite quick.

22. What are object prototypes?

All javascript objects inherit properties from a prototype. For example,

  • Date objects inherit properties from the Date prototype
  • Math objects inherit properties from the Math prototype
  • Array objects inherit properties from the Array prototype.
  • On top of the chain is Object.prototype. Every prototype inherits properties and methods from the Object.prototype.
  • A prototype is a blueprint of an object. The prototype allows us to use properties and methods on an object even if the properties and methods do not exist on the current object.

Let’s see prototypes help us use methods and properties:

problem solving interview questions for java

In the code above, as one can see, we have not defined any property or method called push on the array “arr” but the javascript engine does not throw an error.

The reason is the use of prototypes. As we discussed before, Array objects inherit properties from the Array prototype.

The javascript engine sees that the method push does not exist on the current array object and therefore, looks for the method push inside the Array prototype and it finds the method.

Whenever the property or method is not found on the current object, the javascript engine will always try to look in its prototype and if it still does not exist, it looks inside the prototype's prototype and so on.

23. What are callbacks?

A callback is a function that will be executed after another function gets executed. In javascript, functions are treated as first-class citizens, they can be used as an argument of another function, can be returned by another function, and can be used as a property of an object.

Functions that are used as an argument to another function are called callback functions. Example:

  • In the code above, we are performing mathematical operations on the sum of two numbers. The operationOnSum function takes 3 arguments, the first number, the second number, and the operation that is to be performed on their sum (callback).
  • Both divideByHalf and multiplyBy2 functions are used as callback functions in the code above.
  • These callback functions will be executed only after the function operationOnSum is executed.
  • Therefore, a callback is a function that will be executed after another function gets executed.

24. What are the types of errors in javascript?

There are two types of errors in javascript.

  • Syntax error : Syntax errors are mistakes or spelling problems in the code that cause the program to not execute at all or to stop running halfway through. Error messages are usually supplied as well.
  • Logical error : Reasoning mistakes occur when the syntax is proper but the logic or program is incorrect. The application executes without problems in this case. However, the output findings are inaccurate. These are sometimes more difficult to correct than syntax issues since these applications do not display error signals for logic faults.

25. What is memoization?

Memoization is a form of caching where the return value of a function is cached based on its parameters. If the parameter of that function is not changed, the cached version of the function is returned. Let’s understand memoization, by converting a simple function to a memoized function:

Note- Memoization is used for expensive function calls but in the following example, we are considering a simple function for understanding the concept of memoization better.

Consider the following function:

In the code above, we have written a function that adds the parameter to 256 and returns it. When we are calling the function addTo256 again with the same parameter (“20” in the case above), we are computing the result again for the same parameter. Computing the result with the same parameter, again and again, is not a big deal in the above case, but imagine if the function does some heavy-duty work, then, computing the result again and again with the same parameter will lead to wastage of time.

This is where memoization comes in, by using memoization we can store(cache) the computed results based on the parameters. If the same parameter is used again while invoking the function, instead of computing the result, we directly return the stored (cached) value.

Let’s convert the above function addTo256, to a memoized function:

In the code above, if we run the memoizedFunc function with the same parameter, instead of computing the result again, it returns the cached result.

Note- Although using memoization saves time, it results in larger consumption of memory since we are storing all the computed results.

26. What is recursion in a programming language?

Recursion is a technique to iterate over an operation by having a function call itself repeatedly until it arrives at a result.

Example of a recursive function: The following function calculates the sum of all the elements in an array by using recursion:

27. What is the use of a constructor function in javascript?

Constructor functions are used to create objects in javascript.

When do we use constructor functions?

If we want to create multiple objects having similar properties and methods, constructor functions are used.

Note- The name of a constructor function should always be written in Pascal Notation: every word should start with a capital letter.

In the code above, we have created a constructor function named Person. Whenever we want to create a new object of the type Person, We need to create it using the new keyword:

The above line of code will create a new object of the type Person. Constructor functions allow us to group similar objects.

28. What is DOM?

  • DOM stands for Document Object Model.  DOM is a programming interface for HTML and XML documents.
  • When the browser tries to render an HTML document, it creates an object based on the HTML document called DOM. Using this DOM, we can manipulate or change various elements inside the HTML document.
  • Example of how HTML code gets converted to DOM:

problem solving interview questions for java

29. Which method is used to retrieve a character from a certain index?

The charAt() function of the JavaScript string finds a char element at the supplied index. The index number begins at 0 and continues up to n-1, Here n is the string length. The index value must be positive, higher than, or the same as the string length.

30. What do you mean by BOM?

Browser Object Model is known as BOM. It allows users to interact with the browser. A browser's initial object is a window. As a result, you may call all of the window's functions directly or by referencing the window. The document, history, screen, navigator, location, and other attributes are available in the window object.

31. What is the distinction between client-side and server-side JavaScript?

Client-side JavaScript is made up of two parts, a fundamental language and predefined objects for performing JavaScript in a browser. JavaScript for the client is automatically included in the HTML pages. At runtime, the browser understands this script.

problem solving interview questions for java

Server-side JavaScript, involves the execution of JavaScript code on a server in response to client requests. It handles these requests and delivers the relevant response to the client, which may include client-side JavaScript for subsequent execution within the browser.

JavaScript Interview Questions for Experienced

1. what are arrow functions.

Arrow functions were introduced in the ES6 version of javascript. They provide us with a new and shorter syntax for declaring functions. Arrow functions can only be used as a function expression. Let’s compare the normal function declaration and the arrow function declaration in detail:

Arrow functions are declared without the function keyword. If there is only one returning expression then we don’t need to use the return keyword as well in an arrow function as shown in the example above. Also, for functions having just one line of code, curly braces { } can be omitted.

If the function takes in only one argument, then the parenthesis () around the parameter can be omitted as shown in the code above. 

The biggest difference between the traditional function expression and the arrow function is the handling of this keyword. By general definition, this keyword always refers to the object that is calling the function. As you can see in the code above, obj1.valueOfThis() returns obj1 since this keyword refers to the object calling the function.

In the arrow functions, there is no binding of this keyword. This keyword inside an arrow function does not refer to the object calling it. It rather inherits its value from the parent scope which is the window object in this case. Therefore, in the code above, obj2.valueOfThis() returns the window object.

2. What do mean by prototype design pattern?

The Prototype Pattern produces different objects, but instead of returning uninitialized objects, it produces objects that have values replicated from a template – or sample – object. Also known as the Properties pattern, the Prototype pattern is used to create prototypes.

The introduction of business objects with parameters that match the database's default settings is a good example of where the Prototype pattern comes in handy. The default settings for a newly generated business object are stored in the prototype object.

The Prototype pattern is hardly used in traditional languages, however, it is used in the development of new objects and templates in JavaScript, which is a prototypal language.

3. Differences between declaring variables using var, let and const.

Before the ES6 version of javascript, only the keyword var was used to declare variables. With the ES6 Version, keywords let and const were introduced to declare variables.

Let’s understand the differences with examples:

  • The variables declared with the let keyword in the global scope behave just like the variable declared with the var keyword in the global scope.
  • Variables declared in the global scope with var and let keywords can be accessed from anywhere in the code.
  • But, there is one difference! Variables that are declared with the var keyword in the global scope are added to the window/global object. Therefore, they can be accessed using window.variableName. Whereas, the variables declared with the let keyword are not added to the global object, therefore, trying to access such variables using window.variableName results in an error.

var vs let in functional scope

Variables are declared in a functional/local scope using var and let keywords behave exactly the same, meaning, they cannot be accessed from outside of the scope. 

  • In javascript, a block means the code written inside the curly braces {} .
  • Variables declared with var keyword do not have block scope. It means a variable declared in block scope {} with the var keyword is the same as declaring the variable in the global scope.
  • Variables declared with let keyword inside the block scope cannot be accessed from outside of the block.

Const keyword

  • Variables with the const keyword behave exactly like a variable declared with the let keyword with only one difference, any variable declared with the const keyword cannot be reassigned.

In the code above, although we can change the value of a property inside the variable declared with const keyword, we cannot completely reassign the variable itself.

4. What is the rest parameter and spread operator?

Both rest parameter and spread operator were introduced in the ES6 version of javascript. Rest parameter ( … ):

  • It provides an improved way of handling the parameters of a function.
  • Using the rest parameter syntax, we can create functions that can take a variable number of arguments.
  • Any number of arguments will be converted into an array using the rest parameter.
  • It also helps in extracting all or some parts of the arguments.
  • Rest parameters can be used by applying three dots (...) before the parameters.

**Note- Rest parameter should always be used at the last parameter of a function:

  • Spread operator (…): Although the syntax of the spread operator is exactly the same as the rest parameter, the spread operator is used to spreading an array, and object literals. We also use spread operators where one or more arguments are expected in a function call.
***Note- Key differences between rest parameter and spread operator: Rest parameter is used to take a variable number of arguments and turns them into an array while the spread operator takes an array or an object and spreads it Rest parameter is used in function declaration whereas the spread operator is used in function calls.

5. In JavaScript, how many different methods can you make an object?

In JavaScript, there are several ways to declare or construct an object.

  • using Class.
  • create Method.
  • Object Literals.
  • using Function.
  • Object Constructor.

6. What is the use of promises in javascript?

Promises are used to handle asynchronous operations in javascript. Before promises, callbacks were used to handle asynchronous operations. But due to the limited functionality of callbacks, using multiple callbacks to handle asynchronous code can lead to unmanageable code. Promise object has four states -

  • Pending - Initial state of promise. This state represents that the promise has neither been fulfilled nor been rejected, it is in the pending state.
  • Fulfilled - This state represents that the promise has been fulfilled, meaning the async operation is completed.
  • Rejected - This state represents that the promise has been rejected for some reason, meaning the async operation has failed.
  • Settled - This state represents that the promise has been either rejected or fulfilled.

A promise is created using the Promise constructor which takes in a callback function with two parameters, resolve and reject respectively.

problem solving interview questions for java

resolve is a function that will be called when the async operation has been successfully completed. reject is a function that will be called, when the async operation fails or if some error occurs. Example of a promise: Promises are used to handle asynchronous operations like server requests, for ease of understanding, we are using an operation to calculate the sum of three elements. In the function below, we are returning a promise inside a function:

In the code above, we are calculating the sum of three elements, if the length of the elements array is more than 3, a promise is rejected, or else the promise is resolved and the sum is returned.

We can consume any promise by attaching then() and catch() methods to the consumer.

problem solving interview questions for java

then() method is used to access the result when the promise is fulfilled.

catch() method is used to access the result/error when the promise is rejected. In the code below, we are consuming the promise:

7. What are classes in javascript?

Introduced in the ES6 version, classes are nothing but syntactic sugars for constructor functions. They provide a new way of declaring constructor functions in javascript.  Below are the examples of how classes are declared and used:

Key points to remember about classes:

  • Unlike functions, classes are not hoisted. A class cannot be used before it is declared.
  • A class can inherit properties and methods from other classes by using the extend keyword.
  • All the syntaxes inside the class must follow the strict mode(‘use strict’) of javascript. An error will be thrown if the strict mode rules are not followed.

8. What are generator functions?

Introduced in the ES6 version, generator functions are a special class of functions. They can be stopped midway and then continue from where they had stopped. Generator functions are declared with the function* keyword instead of the normal function keyword:

In normal functions, we use the return keyword to return a value and as soon as the return statement gets executed, the function execution stops:

In the case of generator functions, when called, they do not execute the code, instead, they return a generator object . This generator object handles the execution.

The generator object consists of a method called next() , this method when called, executes the code until the nearest yield statement, and returns the yield value. For example, if we run the next() method on the above code:

As one can see the next method returns an object consisting of a value and done properties.  Value property represents the yielded value. Done property tells us whether the function code is finished or not. (Returns true if finished).

Generator functions are used to return iterators. Let’s see an example where an iterator is returned:

As you can see in the code above, the last line returns done:true , since the code reaches the return statement.

9. Explain WeakSet in javascript.

In javascript, a Set is a collection of unique and ordered elements. Just like Set, WeakSet is also a collection of unique and ordered elements with some key differences:

  • Weakset contains only objects and no other type.
  • An object inside the weakset is referenced weakly. This means, that if the object inside the weakset does not have a reference, it will be garbage collected.
  • Unlike Set, WeakSet only has three methods, add() , delete() and has() .

10. Why do we use callbacks?

A callback function is a method that is sent as an input to another function (now let us name this other function "thisFunction"), and it is performed inside the thisFunction after the function has completed execution.

JavaScript is a scripting language that is based on events. Instead of waiting for a reply before continuing, JavaScript will continue to run while monitoring for additional events. Callbacks are a technique of ensuring that a particular code does not run until another code has completed its execution.

11. Explain WeakMap in javascript.

In javascript, Map is used to store key-value pairs. The key-value pairs can be of both primitive and non-primitive types. WeakMap is similar to Map with key differences:

  • The keys and values in weakmap should always be an object.
  • If there are no references to the object, the object will be garbage collected.

12. What is Object Destructuring?

Object destructuring is a new way to extract elements from an object or an array.

  • Object destructuring: Before ES6 version:

The same example using object destructuring:

As one can see, using object destructuring we have extracted all the elements inside an object in one line of code. If we want our new variable to have the same name as the property of an object we can remove the colon:

  • Array destructuring: Before ES6 version:

13. Difference between prototypal and classical inheritance

Programers build objects, which are representations of real-time entities, in traditional OO programming. Classes and objects are the two sorts of abstractions. A class is a generalization of an object, whereas an object is an abstraction of an actual thing. A Vehicle, for example, is a specialization of a Car. As a result, automobiles (class) are descended from vehicles (object).

Classical inheritance differs from prototypal inheritance in that classical inheritance is confined to classes that inherit from those remaining classes, but prototypal inheritance allows any object to be cloned via an object linking method. Despite going into too many specifics, a prototype essentially serves as a template for those other objects, whether they extend the parent object or not.

14. What is a Temporal Dead Zone?

Temporal Dead Zone is a behaviour that occurs with variables declared using let and const keywords. It is a behaviour where we try to access a variable before it is initialized. Examples of temporal dead zone:

In the code above, both in the global scope and functional scope, we are trying to access variables that have not been declared yet. This is called the Temporal Dead Zone .

15. What do you mean by JavaScript Design Patterns?

JavaScript design patterns are repeatable approaches for errors that arise sometimes when building JavaScript browser applications. They truly assist us in making our code more stable.

They are divided mainly into 3 categories 

  • Creational Design Pattern
  • Structural Design Pattern
  • Behavioral Design Pattern.
  • Creational Design Pattern: The object generation mechanism is addressed by the JavaScript Creational Design Pattern. They aim to make items that are appropriate for a certain scenario.
  • Structural Design Pattern: The JavaScript Structural Design Pattern explains how the classes and objects we've generated so far can be combined to construct bigger frameworks. This pattern makes it easier to create relationships between items by defining a straightforward way to do so.
  • Behavioral Design Pattern: This design pattern highlights typical patterns of communication between objects in JavaScript. As a result, the communication may be carried out with greater freedom.

16. Is JavaScript a pass-by-reference or pass-by-value language?

The variable's data is always a reference for objects, hence it's always pass by value. As a result, if you supply an object and alter its members inside the method, the changes continue outside of it. It appears to be pass by reference in this case. However, if you modify the values of the object variable, the change will not last, demonstrating that it is indeed passed by value.

17. Difference between Async/Await and Generators usage to achieve the same functionality.

  • Generator functions are run by their generator yield by yield which means one output at a time, whereas Async-await functions are executed sequentially one after another.
  • Async/await provides a certain use case for Generators easier to execute.
  • The output result of the Generator function is always value: X, done: Boolean, but the return value of the Async function is always an assurance or throws an error.

18. What are the primitive data types in JavaScript?

A primitive is a data type that isn't composed of other data types. It's only capable of displaying one value at a time. By definition, every primitive is a built-in data type (the compiler must be knowledgeable of them) nevertheless, not all built-in datasets are primitives. In JavaScript, there are 5 different forms of basic data. The following values are available:

19. What is the role of deferred scripts in JavaScript?

The processing of HTML code while the page loads are disabled by nature till the script hasn't halted. Your page will be affected if your network is a bit slow, or if the script is very hefty. When you use Deferred, the script waits for the HTML parser to finish before executing it. This reduces the time it takes for web pages to load, allowing them to appear more quickly.

20. What has to be done in order to put Lexical Scoping into practice?

To support lexical scoping, a JavaScript function object's internal state must include not just the function's code but also a reference to the current scope chain.

21. What is the purpose of the following JavaScript code?

Every executing function, code block, and script as a whole in JavaScript has a related object known as the Lexical Environment. The preceding code line returns the value in scope.

JavaScript Coding Interview Questions

1. guess the outputs of the following codes:.

  • Code 1 - Outputs 2 and 12 . Since, even though let variables are not hoisted, due to the async nature of javascript, the complete function code runs before the setTimeout function. Therefore, it has access to both x and y.
  • Code 2 - Outputs 3 , three times since variable declared with var keyword does not have block scope. Also, inside the for loop, the variable i is incremented first and then checked.
  • Code 3 - Output in the following order:

Even though the second timeout function has a waiting time of zero seconds, the javascript engine always evaluates the setTimeout function using the Web API, and therefore, the complete function executes before the setTimeout function can execute.

2. Guess the outputs of the following code:

Answers: Code 1 - Output will be {name: “Akki”}. Adding objects as properties of another object should be done carefully. Writing x[y] = {name:”Vivek”} , is same as writing x[‘object Object’] = {name:”Vivek”} , While setting a property of an object, javascript coerces the parameter into a string. Therefore, since y is an object, it will be converted to ‘object Object’. Both x[y] and x[z] are referencing the same property. Code 2 - Outputs in the following order:

Code 3 - Output in the following order due to equality coercion:

3. Guess the output of the following code:

Output is NaN . random() function has functional scope since x is declared and hoisted in the functional scope. Rewriting the random function will give a better idea about the output:

4. Guess the outputs of the following code:

Answers: Code 1 - Output in the following order:

Reason - The first output is undefined since when the function is invoked, it is invoked referencing the global object:

Code 2 - Outputs in the following order:

Since we are using the arrow function inside func2, this keyword refers to the global object. Code 3 - Outputs in the following order:

Only in the IIFE inside the function f , this keyword refers to the global/window object.  

5. Guess the outputs of the following code:

**note - code 2 and code 3 require you to modify the code, instead of guessing the output..

Answers - Code 1 - Outputs 45 . Even though a is defined in the outer function, due to closure the inner functions have access to it. Code 2 - This code can be modified by using closures,

Code 3 - Can be modified in two ways: Using let keyword:

Using closure:

6. Write a function that performs binary search on a sorted array.

function binarySearch ( arr,value,startPos,endPos ) { if (startPos > endPos) return - 1 ; let middleIndex = Math .floor(startPos+endPos)/ 2 ; if (arr[middleIndex] === value) return middleIndex; elsif ( arr[middleIndex] > value ) { return binarySearch(arr,value,startPos,middleIndex- 1 ); } else { return binarySearch(arr,value,middleIndex+ 1 ,endPos); } }  

7. Implement a function that returns an updated array with r right rotations on an array of integers a .

Given the following array: [2,3,4,5,7] Perform 3 right rotations: First rotation : [7,2,3,4,5] , Second rotation : [5,7,2,3,4] and, Third rotation: [4,5,7,2,3]

return [4,5,7,2,3]

8. Write the code for dynamically inserting new components.

<html> <head> <title>inserting new components dynamically</title> <script type="text/javascript"> function addNode () { var newP = document. createElement("p"); var textNode = document.createTextNode(" This is other node"); newP.appendChild(textNode); document.getElementById("parent1").appendChild(newP); } </script> </head> <body> <p id="parent1">firstP<p> </body> </html>

9. Write the code given If two strings are anagrams of one another, then return true.

var firstWord = "Deepak" ; var secondWord = "Aman" ; isAnagram(wordOne, wordTwo); // true function isAnagram ( one, two ) { //Change both words to lowercase for case insensitivity.. var a = one.toLowerCase(); var b = two.toLowerCase(); // Sort the strings, then combine the array to a string. Examine the outcomes. a = a.split( "" ).sort().join( "" ); b = b.split( "" ).sort().join( "" ); return a === b; }

10. Write the code to find the vowels

const findVowels = str => { let count = 0 const vowels = [ 'a' , 'e' , 'i' , 'o' , 'u' ] for ( let char of str.toLowerCase()) { if (vowels.includes(char)) { count++ } } return count }

11. In JavaScript, how do you turn an Object into an Array []?

let obj = { id : "1" , name : "user22" , age : "26" , work : "programmer" }; //Method 1: Convert the keys to Array using - Object.keys() console .log( Object .keys(obj)); // ["id", "name", "age", "work"] // Method 2 Converts the Values to Array using - Object.values() console .log( Object .values(obj)); // ["1", "user22r", "26", "programmer"] // Method 3 Converts both keys and values using - Object.entries() console .log( Object .entries(obj)); //[["id", "1"],["name", "user22"],["age", "26"],["work", “programmer"]]

12. What is the output of the following code?

It is preferable to keep the JavaScript, CSS, and HTML in distinct Separate 'javascript' files. Dividing the code and HTML sections will make them easier to understand and deal with. This strategy is also simpler for several programmers to use at the same time. JavaScript code is simple to update. Numerous pages can utilize the same group of JavaScript Codes. If we utilize External JavaScript scripts and need to alter the code, we must do it just once. So that we may utilize a number and maintain it much more easily. Remember that professional experience and expertise are only one aspect of recruitment. Previous experience and personal skills are both vital in landing (or finding the ideal applicant for the job.

Remember that many JavaScript structured interviews are free and have no one proper answer. Interviewers would like to know why you answered the way you did, not if you remembered the answer. Explain your answer process and be prepared to address it. If you're looking to further enhance your JavaScript skills, consider enrolling in this free JavaScript course by Scaler Topics to gain hands-on experience and improve your problem-solving abilities.

Recommended Resources

  • JavaScript Cheat Sheet: Basics to Advanced(2023)
  • Online Javascript Compiler
  • Top JavaScript Features You Must Know
  • 50 JavaScript MCQ With Answers
  • Top 15+ JavaScript Projects for Beginners to Advanced [With Source Code]
  • 9 Best JavaScript IDE & Source Code Editors [2023]
  • Top ES6 Interview Questions (2023)
  • 10 Best JavaScript Books for Beginners to Advanced [2023]
  • 30+ Top Node.js Interview Questions (2023)
  • Typescript vs Javascript: What’s The Difference?
  • Top 5 JavaScript Libraries You Must Know in 2023
  • Difference Between HTML and JavaScript
  • Javascript Vs jQuery: What’s the Difference? [2023]
  • Javascript Vs Python: What’s The Difference? [2023]
  • Difference Between Java and Javascript
  • Difference between Typescript and Javascript

Interview Guides

  • The Ultimate Guide to Acing Your Technical Interview
  • 300+ Must Do Coding Questions from Interviews
  • Mock Interview
  • InterviewBit - No.1 Resource for Tech Interview Preparation

Coding Problems

Javascript mcq.

Which of the following statements regarding JavaScript is true?

Which of the following JavaScript code snippets will provide the desired result?

In JavaScript, which of the following is not a bug?

JavaScript was created by which company?

What do you mean by block statement in JavaScript?

Argument class is

Which of these String object functions gives the calling data type transformed to upper case?

The JSON() method's property is

Which of the below do not belong in the JavaScript Data Types category?

The interpreter for Javascript is

  • Privacy Policy

instagram-icon

  • Practice Questions
  • Programming
  • System Design
  • Fast Track Courses
  • Online Interviewbit Compilers
  • Online C Compiler
  • Online C++ Compiler
  • Online Java Compiler
  • Online Python Compiler
  • Interview Preparation
  • Java Interview Questions
  • Sql Interview Questions
  • Python Interview Questions
  • Javascript Interview Questions
  • Angular Interview Questions
  • Networking Interview Questions
  • Selenium Interview Questions
  • Data Structure Interview Questions
  • Data Science Interview Questions
  • System Design Interview Questions
  • Hr Interview Questions
  • Html Interview Questions
  • C Interview Questions
  • Amazon Interview Questions
  • Facebook Interview Questions
  • Google Interview Questions
  • Tcs Interview Questions
  • Accenture Interview Questions
  • Infosys Interview Questions
  • Capgemini Interview Questions
  • Wipro Interview Questions
  • Cognizant Interview Questions
  • Deloitte Interview Questions
  • Zoho Interview Questions
  • Hcl Interview Questions
  • Highest Paying Jobs In India
  • Exciting C Projects Ideas With Source Code
  • Top Java 8 Features
  • Angular Vs React
  • 10 Best Data Structures And Algorithms Books
  • Best Full Stack Developer Courses
  • Best Data Science Courses
  • Python Commands List
  • Data Scientist Salary
  • Maximum Subarray Sum Kadane’s Algorithm
  • Python Cheat Sheet
  • C++ Cheat Sheet
  • Javascript Cheat Sheet
  • Git Cheat Sheet
  • Java Cheat Sheet
  • Data Structure Mcq
  • C Programming Mcq
  • Javascript Mcq

1 Million +

IMAGES

  1. Top 100+ Core Java Interview Questions

    problem solving interview questions for java

  2. Best Interview Questions to Ask an Entry Level & Senior Java Developer

    problem solving interview questions for java

  3. Java Interview Questions & Answers Pdf for Freshers 2022- Word & Excel

    problem solving interview questions for java

  4. 100+ Top Java Interview Questions and Answers in 2022

    problem solving interview questions for java

  5. 100 most asked Java Interview Questions and Answers

    problem solving interview questions for java

  6. Best Java Questions For Interview With Answers 2021

    problem solving interview questions for java

VIDEO

  1. JS Problem Solving Questions 01

  2. Mastering Java Interview Questions: Common Challenges and Expert Answers

  3. Fresher Mock Interview Java

  4. The unfair way I got good at Leetcode

  5. Java Interview Questions and Answers with Explanation

  6. My Interview experience with Oracle

COMMENTS

  1. Top 50 Java Programming Interview Questions

    Consider that, for a given number N, if there is a prime number M between 2 to √N (square root of N) that evenly divides it, then N is not a prime number. 5. Write a Java program to print a Fibonacci sequence using recursion. A Fibonacci sequence is one in which each number is the sum of the two previous numbers.

  2. 200+ Core Java Interview Questions and Answers (2024)

    Java Interview Questions and Answers. Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and performance.

  3. 51 Java Programming Interview Questions (And Sample Answers)

    Here's a list of additional java interview questions that hiring managers may ask you: 41. Write a program to sort a sequence of numbers in ascending order. 42. Using Java 8 date-time library in CLASSPATH (package private) file, write a program that shows how you can add time to any time with respect to midnight on Jan. 1, 2000.

  4. The Java Interview Prep Handbook

    Java is well-known for its robustness in Object-Oriented Programming (OOP), and it provides a comprehensive foundation essential for developers at every level. This handbook offers a detailed pathway to help you excel in Java interviews. It focuses on delivering insights and techniques relevant to roles in esteemed big tech companies, ensuring ...

  5. 21 Essential Java Interview Questions

    In Java, Strings are immutable and are stored in the String pool. What this means is that, once a String is created, it stays in the pool in memory until being garbage collected. Therefore, even after you're done processing the string value (e.g., the password), it remains available in memory for an indeterminate period of time thereafter (again, until being garbage collected) which you have ...

  6. Java Interview Questions and Programming Examples

    As per my experience, most of the questions are related to: the programming language particularities (syntax, core API) problem solving (algorithms, data structures) application design / architecture (design patterns, object oriented programming, best practices…). You'll find below a summary of these question categories and some examples.

  7. 300 Core Java Interview Questions (2023)

    300 Core Java Interview Questions | Set 1. There is the list of 300 core Java interview questions. If there is any core Java interview question that has been asked to you, kindly post it in the ask question section. We assure that you will get here the 90% frequently asked interview questions and answers.

  8. Top 20 Java coding interview questions for 2024

    Coding interviews are aimed at gauging how well-prepared a candidate is in terms of language proficiency, foundational knowledge, problem-solving skills, and soft skills. For a position that explicitly mentions a language, such as a job listing for a Java developer, it makes even more sense to spend some time and energy polishing Java skills by exploring the common interview questions asked in ...

  9. Java 8 Interview Questions(+ Answers)

    In Java 8, this problem was solved by using the default method. For example, the Collection interface does not have a forEach method declaration. Thus adding such a method would simply break the whole collections API. ... In this article, we explored several important technical interview questions with a bias on Java 8. This is by no means an ...

  10. 50+ Important Java Interview Questions and Answers to Know

    Hopefully, you've found these interview questions useful when vetting Java developers. Keep in mind that the technical interview is just one portion of the hiring process. Whether you're hiring freelance or full-time Java developers, you also want to evaluate their soft skills like communication, problem-solving, time management, and more.

  11. Top 80 Java Interview Questions and Answers [2024]

    Two important properties of a Java object are behavior and state. An object is created as soon as the JVM comes across the new keyword. 17. Define classes in Java. A class is a collection of objects of similar data types. Classes are user-defined data types and behave like built-in types of a programming language.

  12. 50 Java Interview Questions and Answers in 2024

    The necessity for Java Interview Questions lies in their ability to evaluate a candidate's technical skill set, practical problem-solving abilities, and up-to-date knowledge of the language. These questions have limitations, including a focus on theoretical knowledge and a neglect of soft skills assessment.

  13. 42 Advanced Java Interview Questions For Senior Developers

    Java 165. Answer. The JVM has a heap that is the runtime data area from which memory for all class instances and arrays is allocated. It is created at the JVM start-up. Heap memory for objects is reclaimed by an automatic memory management system which is known as a garbage collector.

  14. Core Java Interview Questions and Answers (2024)

    Write a Java Program to check if any number is a magic number or not. A number is said to be a magic number if after doing sum of digits in each step and inturn doing sum of digits of that sum, the ultimate result (when there is only one digit left) is 1. Example, consider the number: Step 1: 163 => 1+6+3 = 10.

  15. GitHub

    Top interview problem solving questions solved in Java. - Pierre-Malak/ProblemSolving-Interview

  16. Java Coding Interview Questions You Need to Know

    Java coding interview questions are important because they help hiring managers evaluate a candidate's technical skills and problem-solving abilities. Interviewers can assess a candidate's understanding of Java fundamentals, coding practices, and ability to apply Java concepts to real-world scenarios by asking specific Java coding questions.

  17. Top 75 Programming Interview Questions Answers to Crack Any ...

    1. Array-based Programming Interview Questions. If you ask me just one topic to prepare really well for coding interviews, I would pick the array. It's one of the essential data structures and favorite darling of coding interviews. There are so many popular coding interview questions that are based upon the array, some of them are easy and some ...

  18. Java Exercises

    We hope these exercises have helped you understand Java better and you can solve beginner to advanced-level questions on Java programming. Solving these Java programming exercise questions will not only help you master theory concepts but also grasp their practical applications, which is very useful in job interviews. More Java Practice Exercises

  19. 10 Java Interview Questions You Should Know

    Complete the given code so that it outputs the area of a parallelogram with breadth B and height H. You should read the variables from the standard input. If B <= 0 or H <= 0, the output should be "java.lang.Exception: Breadth and height must be positive" without quotes. Input Format. There are two lines of input.

  20. Solve Java

    Join over 23 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.

  21. Top 20 Problem Solving Interview Questions (Example Answers Included)

    MIKE'S TIP: When you're answering this question, quantify the details. This gives your answer critical context and scale, showcasing the degree of challenge and strength of the accomplishment. That way, your answer is powerful, compelling, and, above all, thorough. 2. Describe a time where you made a mistake.

  22. Top 50 Java Programs from Coding Interviews

    For example, 153 is an Armstrong number because of 153= 1+ 125+27, which is equal to 1^3+5^3+3^3. You need to write a program to check if the given number is Armstrong number or not. 6. Avoiding deadlock in Java ( solution) This is one of the interesting programs from Java Interviews, mostly asked to 2 to 3 years of experienced programmers or ...

  23. Problems

    Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

  24. Top 50 Array Coding Problems for Interviews

    Find the first repeating element in an array of integers. Solve. Find the first non-repeating element in a given array of integers. Solve. Subarrays with equal 1s and 0s. Solve. Rearrange the array in alternating positive and negative items. Solve. Find if there is any subarray with a sum equal to zero.

  25. JavaScript Interview Questions from Beginner to Advanced Levels

    Whether hiring for an entry-level web developer position or a web architect, asking the right JavaScript coding questions lets you assess the candidate's depth of knowledge in core JavaScript concepts, problem-solving skills, and understanding of modern JavaScript practices.. More than identifying which people in your pool of applicants can answer technical questions, these JavaScript ...

  26. JavaScript Interview Questions and Answers (2024)

    Learn and Practice on almost all coding interview questions asked historically and get referred to the best tech companies ... consider enrolling in this free JavaScript course by Scaler Topics to gain hands-on experience and improve your problem-solving abilities. Recommended Resources. JavaScript Cheat Sheet: Basics to Advanced(2023 ...