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

  • 800+ Q&As Menu

Prepare by categories …

  • Why java-success.com?
  • What are the benefits?
  • PDF downloads
  • Privacy Policy
  • 100+ Free Java Interview Q&As
  • 300+ Java Interview FAQs
  • 150+ Java Architect Interview FAQs
  • 150+ Spring & Hibernate interview FAQs
  • 150+ Java coding interview Q&As
  • 150+ Java code quality interview Q&As
  • 100+ Free Big Data Interview Q&As
  • 300+ Big Data Interview FAQs
  • 150+ SQL interview questions
  • 200+ Python interview questions
  • 250+ Scala interview questions
  • Your - Resume writing skills
  • Your - Resume samples
  • Your - Job interviews
  • Your - Job hunting tips
  • Your - Job offers 2-6?
  • Your - Earning more?
  • Your - Freelancing
  • Your - Feeling stagnated?
  • Your - Self-taught success?
  • Your - Soft skills
  • Your - Lack of motivation?
  • Your - Certification
  • Your - Blogging benefits
  • Your - Philosophies
  • Your - Rants
  • Membership Levels
  • Membership Billing
  • Membership Checkout
  • Membership Invoice
  • Membership Account
  • Membership Cancel

18 Java scenarios based interview Q&As for the experienced – Part 1

Let’s look at scenarios or problem statements & how would you go about handling those scenarios in Java. These scenarios interview questions will judge your Java experience. Full list of Java scenarios based interview questions are covered at Judging your Java experience via scenarios based interview Q&As .

#1. Caching

Q01.Scenario : You need to load stock exchange security codes with price from a database and cache them for performance. The security codes need to be refreshed say every 30 minutes. This cached data needs to be populated and refreshed by a single writer thread and read by several reader threads. How will you ensure that your read/write solution is scalable and thread safe?

Cache for read performance

Cache for read performance

A01. Solution : There are a number of options as described below:

Option 1 : The java.util.concurrent.locks package provides classes that implement read/write locks where the read lock can be executed in parallel by multiple threads and the write lock can be held by only a single thread. The ReadWriteLock interface maintains a pair of associated locks, one for read-only and one for writing. The readLock( ) may be held simultaneously by multiple reader threads, while the writeLock( ) is exclusive. In general, this implementation improves performance and scalability when compared to the mutex locks (i.e. via synchronized key word) when

1. There are more reads and read duration compared to writes and write duration .

2. It also depends on the machine you are running on — for example, multi-core processors for better parallelism .

Here is another approach step by step: Simple caching Java application step by step

Option 2 : The ConcurrentHashmap is another example where improved performance can be achieved when you have more reads than writes . The ConcurrentHashmap allows concurrent reads and locks only the buckets that are used for modification or insertion of data.

Option 3 : Making use of caching frameworks like EHCache , OSCache , etc. Caching frameworks take care of better memory management with LRU (Least Recently Used) and FIFO(First In First Out) eviction strategies, disk overflow, data expiration and many other optional advanced features, as opposed to writing your own.

Here is a working example in Java to Implement an in-memory LRU cache in Java with TTL without using a framework like EHCache.

Option 4 : Using a distributed & an in memory database like Redis . Redis can be a choice for implementing a highly available in-memory cache to decrease data access latency, increase throughput, and ease the load off your relational or NoSQL database and application.

#2. Asynchronus processing

Q02. Scenario : If you have a requirement to generate online reports or feed files by pulling out millions of historical records from a database, what questions will you ask, and how will you go about designing it?

A02. Designing a system is all about asking the right questions to gather requirements.

— Online Vs Offline? Should we restrict the online reports for only last 12 months of data to minimise the report size and to get better performance, and provide reports/feeds for the data older than 12 months via offline processing? For example, Bank statements for last 12 months via online & for transactions older than 12 months via offline asynchronous processing without blocking the customer from browsing rest of the website. Reports can be generated asynchronously and once ready can be emailed or downloaded via a URL at a later time.

— What report generation framework to use like Jasper Reports , Open CSV , XSL-FO with Apache FOP , etc depending on the required output formats?

— How to handle exceptional scenarios? send an error email, use a monitoring system like Tivoli or Nagios to raise production support tickets on failures, etc?

— Security requirements. Are we sending feed/report with PII (i.e. Personally Identifiable Information) data via email? Do we need proper access control to restrict who can generate which online reports? Should we password protect the email attachments? Are there any compliance or regulatory requirements like PCI (i.e. Payment Card Industry), GDPR (i.e. General Data Protection Regulation), ACCC (i.e. Australian Competition and Consumer Commission), etc depending on the jurisdictions served by the application?

— Should we schedule the offline reports to run during off peak time ? For example, enter all the requests for a report into a “ Request ” table and then schedule a process to run at say midnight to refer to all pending requests in the “ Request ” table to generate and store the relevant reports in an outbox for the customers to download. An email can be sent to clients with the report URL to download the report.

— Archival and purging straggles of the historical reports. What is the report retention period for the requirements relating to auditing and compliance purpose? How big are the files?

Solution : An online application with a requirement to produce time consuming reports or a business process (e.g. re-balancing accounts, aggregating hierarchical information, etc) could benefit from making these long running operations asynchronous. Once the reports or the long running business process is completed, the outcome can be communicated to the user via emails or asynchronously refreshing the web page via techniques known as “ server push (JEE Async Servlet)” or “ client pull (Refresh meta tag)”. A typical example would be

a) A user makes an online request for an aggregate report or a business process like re-balancing his/her portfolios.

b) The user request will be saved to a database table for a separate process to periodically pick it up and process it asynchronously.

c) The user could now continue to perform other functionality of the website without being blocked .

d) A separate process running on the same machine or different machine can periodically scan the table for any entries and produce the necessary reports or execute the relevant business process. This could be a scheduled job that runs once during off-peak or every 10 minutes. This depends on the business requirement.

e) Once the report or the process is completed, notify the user via emails or making the report available online to be downloaded.

Offline report generation on AWS cloud

Offline report generation on AWS cloud

#3 Regular Expressions (i.e. regex)

Q03. Scenario : You need to find and change a text from “Client” to “Customer” in 300+ html files.

A03. Solution : Harness the power of Unix & Regex .

sed and awk are very powerful Unix commands for file manipulations. These are covered in detail in The Unix interview Q&As .

#4 Auditing

Q04. Scenario : You have a requirement to maintain a history of insertion, modification, and deletion to the “Customer” table. How will you go about accomplishing this?

A04. Solution

1) Create an ETL (i.e. Extract Transform & Load) batch job that periodically extracts all the changes to batch files and send those files to a Data warehouse system, which loads these batch files to a SCD Type 2 history table. SCD Type 2 means maintain each change. This is discussed in detail at 13 Data Warehouse interview Q&As – Fact Vs Dimension, CDC, SCD, etc .

2) Asynchronously via publish & subscription paradigm. Publish each change as an event to a message oriented middle-ware like Apache Kafka, Rabbit MQ, Websphere MQ, etc & separate subscriber application will save each event to a SQL or NoSQL history table.

3) Create database table triggers to insert superseded records to a separate history table. A database trigger is procedural code that is automatically executed in response to certain events like insert, update, etc on a particular table or view in a database. Care must be taken in using or writing triggers as incorrectly written or used triggers can significantly impact performance of your database.

#5 Externalize business rules

Q05. Scenario : You are asked to design an application, which validates data with 100+ rules to comply with the government compliance requirements and tax laws. These compliance requirements can change and the application need to quickly and easily adapt to changing requirements.

A05. Solution : Harness the power of Rules Engines like Drools . Drools is a popular open source business rules and work flow engine. It helps you externalise the rules in database tables or excel spreadsheets as opposed to embedding within the Java code. The rules are executed in the form of when given a ($condition) then execute the ($consequence). The business will be the custodian of these rules that can be easily viewed on an excel spreadsheet or via querying the database tables. A GUI could be built to maintain these rules that reside in a database.

#6 Concurrency Management

Q06. Scenario : Reference counting where a shared resource is incremented or decremented. The increment/decrement operations must be thread safe. For example, a counter that keeps track of the number of active logged in users by incrementing the count when users log in and decrementing the count when the users log out. Sometimes you want to allow a finite number of concurrent accesses say 3 users at a time.

A06. Solution :

Mutex : is a single key to an object (E.g. a toilet). One person can have the key and occupy the toilet at the time. When finished, the person gives (or releases) the key to the next person in the queue. In Java, every object has a mutex and only a single thread can get hold of a mutex .

Semaphore : Is a number of free identical toilet keys. For example, having 3 toilets with identical locks and keys. The semaphore count is set to 3 at beginning and then the count is decremented as people are acquiring the key to the toilets. If all toilets are full, i.e. there are no free keys left, the semaphore count is 0. Now, when one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue.

#7 Designing a trading system

Q07. Scenario : If you are working with an online trading application, you may want the functionality to queue trades placed after hours and process them when the stock market opens. You also need to asynchronously handle the order statuses sent from the stock exchange like partially-filled, rejected, fully filled, etc, and update the online order information. How will you go about solution this?

A07. Solution : The Message Oriented Middle-wares like Apache Kafka, Rabbit MQ, Websphere MQ, webMethods Broker, etc provide features like guaranteed delivery with store-and-forward mechanism, no duplicates, and transaction management for enterprise level program-to-program communications by sending and receiving messages asynchronously (or synchronously). The diagram below gives a big picture.

Screen shot 2014-08-31 at 11.14.08 AM

When using Message Oriented Middle-wares (MOM) to facilitate asynchronous processing

1) The producer (i.e Trading Engine) that submits user requests and consumer (i.e. FIX Router) that converts the messages to FIX protocol and send FIX messages to the Stock Exchange system retain processing control and do not block. In other words, they continue processing regardless of the state of others. Queue depths need to be properly set, and the messages need to be durable . Message correlation ids are used to pair request and response.

2) MOM creates looser coupling among systems, provides delivery guarantees, prevents message losses, scales well by decoupling performance characteristics of each system, has high availability and does not require same time availability of all sub-systems. So, MOM is ideal for geographically dispersed systems requiring flexibility, scalability, and reliability.

3) You may also require to perform logging, auditing and performance metrics gathering asynchronously and non-intrusively. For example, you could send the log messages from log4j to a queue to be processed later asynchronously by a separate process running on the same machine or a separate machine. The performance metrics can be processed asynchronously as well.

For example, a trading application may have a number of synchronous and asynchronous moving parts and metrics needs to be recorded for various operations like placing a trade on to a queue, receiving asynchronous responses from the stock market, correlating order ids, linking similar order ids, etc. A custom metrics gathering solution can be accomplished by logging the relevant metrics to a database and then running relevant aggregate queries or writing to a file system and then running PERL based text searches to aggregate the results to a “csv” based file to be opened and analyzed in a spreadsheet with graphs. In my view, writing to a database provides a greater flexibility. For example, in Java, the following approach can be used.

Asynchronous logging

Asynchronous logging

— Use log4j JMS appender or a custom JMS appender to send log messages to a queue.

— Use this appender in your application via Aspect Oriented Programming (AOP – e.g Spring AOP, AspectJ, etc) or dynamic proxy classes to non-intrusively log relevant metrics to a queue. It is worth looking at Perf4j and context based logging with MDC (Mapped Diagnostic Contexts) or NDC (Nested Diagnostic Contexts) to log on a per thread basis to correlate or link relevant operations.

— A stand-alone listener application needs to be developed to dequeue the performance metrics messages from the queue and write to a database or a file system for further analysis and reporting purpose. This listener could be written in Java as a JMX service using JMS or via broker service like webMethods, TIBCO, etc.

— Finally, relevant SQL or regular expression based queries can be written to aggregate and report relevant metrics in a customized way.

#8 Impact Analysis (aka IA)

Q08. Scenario : You are required to change the logic of a module that many other modules have dependency on. How would you go about making the changes without impacting dependent systems.

A08. Solution : You need to firstly perform an impact analysis . Impact analysis is about being able to tell which pieces of code, packages, modules, and projects use given piece of code, packages, modules, and projects, or vice versa is a very difficult thing.

Performing an impact analysis is not a trivial task, and there is not a single tool that can cater for every scenario. You can make use of some static analysis tools like IDEs (e.g. eclipse), JRipples , X- Ray , etc. But, unfortunately applying just static analysis alone not enough, especially in Java and other modern languages whereas lots of things can happen in run time via reflections, dynamic class loading & configuration, polymorphism, byte code injection, proxies, etc.

a) In eclipse Ctrl+Shift+g c an be used to search for references

b) You can perform a general “File Search” for keywords on all projects in the work-space.

c) You can use Notepad++ editor and select Search –> Find in files. You can search for a URL or any keyword across a number of files within a folder.

There are instances where you need to perform impact analysis across stored procedures, various services, URLs, environment properties, batch processes, etc. This will require a wider analysis across projects and repositories.

Search within your code repository like GIT :

Tools like FishEye can be used to search across various code repositories. FisheEye is not targeted for any special programming language. It just supports various version control systems and the concept of text files being changed over time by various people. Handy for text searches like environment based properties files to change a URL or host name from A to B.

Grep the Unix/Linux environment where your application is deployed.You can perform a search on the file system where your application(s) are deployed.

Analyze across various log files . It is also not easy to monitor service oriented architectures. You can use tools like Splunk to trace transactions across the IT stack while being tested by the testers to proactively identify any issues related to change. Splunk goes across multiple log files.

Conduct impact analysis sessions across cross functional and system teams and communicate the changes . Brain storm major areas affected and document them. Have a manual test plan that covers the impact systems to be tested. Collaborate with cross functional teams and identify any gaps in your analysis. Have a proper review and sign-off process. Get more developers to do peer code reviews.

Have proper documentation with high level architecture diagrams and dependency graphs where possible . As the number systems grow, so does the complexity. A typical enterprise Java application makes use of different database servers, messaging servers, ERP systems, BPM systems, Work flow systems, SOA architectures, etc. Use online document management systems like Confluence or Wiki , which enables search for various documents.

More Java scenarios based interview Q&As

Q09 to Q18: 18 Java scenarios based interview Q&As for the experienced – Part 2

100+ Judging your Java experience

100+ Java scenarios based interview questions & answers .

Top 10 popular posts

CategoryTheoryComposition

500+ Java Interview FAQs

500+ big data interview faqs, 300+ companion tech interview, 16+ java key tech areas, 800+ java questions & answers, java & big data tutorials, taking the roads less travelled ….

No 2 jobs are created the same in terms of pay, opportunities to learn and culture . I strongly believe that know-hows in this site will help you discover the roads less travelled. Don't be overwhelmed by the number of Q&As & tech stacks as nobody knows everything, and often key Q&As at the right moment makes a big difference.

  • Why & how to choose from 2-6 job offers?
  • 9 Tips to earn more as a Java or Big Data Engineer
  • How to open more doors & expand your horizons as a Software or Big Data engineer?
  • A good resume can get you more job interviews
  • Job interviews are not a technical contest to see who gets the most number of questions right
  • Why and how to become a freelancer/contractor ?
  • Latest Posts

Arulkumaran Kumaraswamipillai

  • 800+ Java Interview Questions for 2, 5 and 10+ years of experience - April 3, 2024
  • 500+ Big Data Interview Questions for 2, 5 and 10+ years of experience - April 3, 2024
  • GitOps interview questions & answers - April 3, 2024

Insert/edit link

Enter the destination URL

Or link to existing content

Jinal Desai

DevOps, GCP, etc.

  • 50 Java Interview Questions + 30 Scenario Based Q&A

This is post 2 of 8 in the series “Programming Language Interview Questions”

  • Object Oriented Programming (OOPs) Interview Questions
  • Cracking the Code: 200 Interview Q&A for Software Developers
  • Performance and Optimization Interview Questions
  • Caching Interview Questions and Answers
  • Error Handling and Debugging Interview Questions
  • C Programming Language Interview Questions
  • C++ Programming Interview Questions

Table of Contents

Introduction

Java is one of the most popular and widely used programming languages today. It is important for aspiring Java developers to be well-prepared for technical interviews which typically involve many Java programming questions.

The interviewers often ask a mix of theoretical Java questions to test the conceptual knowledge and practical programming questions to evaluate the coding skills. In this article, we provide a compilation of commonly asked Java interview questions and sample answers to help candidates prepare effectively.

The questions cover core Java basics, OOP concepts, classes and objects, methods and constructors, access modifiers, inheritance, polymorphism, abstraction, interfaces, Java collections, exception handling, multithreading and concurrency. There are also scenario-based Java questions that can be asked in interviews to check how candidates can apply the language features to build real-world applications.

50 interview questions and answers

1. What is Java? Java is a high-level, object-oriented programming language. It is a general-purpose concurrent and class-based language that is designed to have as few implementation dependencies as possible.

2. What are objects and classes in Java? Objects are basic building blocks in Java that contains state and behavior. Classes are templates that define objects and their behavior.

3. What is JVM and JRE? JVM (Java Virtual Machine) is the runtime environment for Java programs. It converts Java bytecode into machine language. JRE (Java Runtime Environment) is the implementation of JVM that provides core libraries and other components to run Java programs.

4. Explain the platform independence of Java. Java is compiled to bytecode that can run on any platform with a JVM. The JVM interprets the bytecode into native machine code. This makes Java platform independent.

5. What are constructors in Java? Constructors are special methods in Java that are used to initialize objects. The constructor is invoked when an object of a class is created. It has the same name as the class and does not have a return type.

6. What is method overloading and overriding in Java? Method overloading is defining methods with the same name but different parameters. Overriding is providing a specific implementation of a method already defined in the parent class.

7. What is abstraction in Java? Abstraction refers to hiding the implementation details and exposing only the functionality to users. Abstract classes and interfaces are used to achieve abstraction in Java.

8. What are Java packages? Packages in Java are collections of related classes and interfaces that are bundled together. Packages provide namespace management and access control in Java.

9. What is final keyword in Java? The final keyword is used to apply restrictions on classes, methods and variables. Final class cannot be inherited, final method cannot be overridden and final variable value cannot be changed.

10. What is static in Java? Static is a keyword in Java used to denote a class member belongs to a type rather than to an instance. Static members can be used without creating an object of class.

11. What is encapsulation in Java? Encapsulation is the mechanism of wrapping data (variables) and code acting on data (methods) together as a single unit. In Java, encapsulation is achieved by making fields private and providing public setter and getter methods.

12. What is inheritance in Java? Inheritance represents parent-child relationship between classes in Java. It allows a derived class to inherit commonly used state and behavior from its parent class.

13. What is polymorphism in Java? Polymorphism means ability to take different forms. In Java, polymorphism allows assigning a variable and method call to take different forms or classes. Method overloading and overriding uses polymorphism.

14. What is JIT compiler in Java? JIT (Just-In-Time) compiler in Java converts bytecode into native machine code at runtime when required by the program. It improves performance by compiling bytecode lazily.

15. What is multithreading in Java? Multithreading allows concurrent execution of multiple parts of a Java program. The main ways to create threads in Java are extending Thread class and implementing Runnable interface.

16. Explain different ways to create a thread in Java. There are two ways to create a thread in Java – 1. Extending Thread class 2. Implementing Runnable Interface. Runnable is preferred because Java does not support multiple inheritance.

17. What are access modifiers in Java? Java provides access control through public, protected, private and default modifiers. Public grants access from anywhere. Private restricts access to the class itself. Default and protected have specialized uses.

18. What is Collections Framework in Java? Java Collections Framework provides ready-made architecture to store and manipulate group of objects. It contains interfaces like List, Set, Queue and classes like ArrayList, LinkedHashSet, PriorityQueue etc.

19. What are different types of inner classes in Java? – Nested (static) inner class – Inner class – Local inner class – Anonymous inner class

They allow logical grouping of classes and interfaces and access to the outer class.

20. What is Java API and where is it documented? Java API (Application Programming Interface) is a collection of pre-built packages, classes and interfaces in Java. It is documented at https://docs.oracle.com/en/java/javase/index.html

21. What is JDBC API in Java? JDBC (Java Database Connectivity) is an API used to connect and execute queries to a database from Java. JDBC provides a set of interfaces that allows connectivity to relational databases.

22. What are the basic interfaces of JDBC API? The core interfaces of JDBC API are – Driver, Connection, Statement and ResultSet that allows connecting and interacting with a database.

23. What are the different types of JDBC drivers? There are 4 types of JDBC drivers: 1. JDBC-ODBC bridge driver 2. Native API driver (partially java driver) 3. Network Protocol driver (fully java driver) 4. Thin driver (fully java driver)

24. What is singleton class in Java and how can we make a class singleton? Singleton class means that only one instance of the class can be created. Singleton pattern involves a single private constructor, a static variable and a static public method that returns the instance.

25. What is Java Serialization API? Java Serialization API provides a standard mechanism to serialize objects to stored or transmitted across streams. Only serializable objects can be serialized.

26. How can we convert bytes to objects and vice-versa in Java? We can convert bytes to objects and vice-versa using serialization and deserialization in Java. ObjectOutputStream is used to convert objects to bytes and ObjectInputStream is used to recreate objects from bytes.

27. What are anonymous inner classes in Java? Anonymous inner classes are inner classes without a name declared and instantiated in a single expression using the new keyword. They are used for inline implementation of interfaces.

28. What is reflection API in Java and why is it useful? Java reflection API allows inspecting and modifying runtime behavior of classes at runtime. It is useful to introspect objects and call methods dynamically at runtime without knowing the names at compile time.

29. What is autoboxing and unboxing in Java? Autoboxing is automatic conversion of primitive types to object wrapper classes. Unboxing is the reverse process of converting wrapper objects to primitives. They were introduced in Java 1.5.

30. What is final, finally and finalize in Java? final is a keyword – final class can’t be inherited, final method can’t be overridden, final variable value can’t change. finally is a block – used with try/catch to put code that executes always. finalize is a method – called by Garbage collector before object is collected.

31. What is try-with-resources in Java? try-with-resources is a way to automatically close resources after usage without needing an explicit finally block. Any class that implements AutoCloseable interface can be used in try-with-resources.

32. What is multi-catch block in Java? A multi-catch block allows handling multiple exceptions in a single catch block instead of using multiple catch blocks for different exceptions. The catch parameter is specified using pipe (|) symbol.

33. What are the advantages of Java? Simple, Object-Oriented, Portable, Platform independent, Secured, Robust, Architecturally neutral, Interpreted, High Performance, Multithreaded, Distributed, Dynamic

34. What are the disadvantages of Java? Not suitable for low-level programming. Limited speed. No unsigned data type. Backward incompatible.

35. What is namespace in Java? Namespace is a naming system to organize classes in Java packages. It resolves naming collisions and confusions and allows fully qualified name to uniquely identify classes, interfaces etc.

36. What is JIT compiler in Java? JIT (Just-In-Time) compiler is used to improve the performance. It converts bytecode into native machine language when required by the running Java program.

37. What is the difference between path and classpath variables? PATH is an environment variable used by operating system to locate executables. Classpath is specific to Java and used by JVM to locate Java bytecode files (classes).

38. What is Anonymous inner class in Java? Anonymous inner class is an inner class without a name declared and instantiated in a single expression using the new operator. Commonly used for simplified event handling.

39. What is difference between Heap and Stack memory? Heap memory is used by all parts of the application whereas stack memory is used only by one thread of execution. Objects are created in Heap, Stack is used for local primitive variables and references to objects in Heap.

40. What is Java String Pool? Java String Pool refers to collection of Strings stored in heap memory. String literals and constants are stored in the String pool for reuse to optimize memory usage.

41. How is a string immutable in Java? In Java, string objects are immutable meaning their state cannot be changed once created. Whenever changes are made to a string, a new instance is created. This optimizes performance by reusing strings from pool.

42. What is ThreadPoolExecutor in Java? ThreadPoolExecutor is a thread pool implementation added from Java 5 that provides more configurable thread pools to execute tasks. It allows configuring pool size, rejection policies, thread factories etc.

43. What is Java Memory Model? It is a specification that describes the shared memory system defined by the Java programming language and virtual machine including visibility and atomicity guarantees on shared data.

44. What is memory leak in Java? Memory leak occurs when objects are no longer used by the application but Garbage Collector fails to recognize them as unused. This results in out of memory errors if too many objects are unreferenced.

45. What is shallow copy and deep copy in Java? Shallow copy is copying an object’s field references into another instance. Deep copy is making separate copy of all the objects in the original object graph.

46. What are transient and volatile keywords in Java? transient – skip field during serialization, volatile – field will not be cached and always read from main memory.

47. What is Executor Framework in Java? The Executor framework in Java provides an abstraction over management of threads. Executors can schedule asynchronous tasks and control concurrency transparently using thread pool.

48. Explain Generics in Java? Generics allow defining type-safe classes, interfaces and methods which work with different types while avoiding duplicity. Generics work only with reference types in Java.

49. What is Comparable and Comparator interface in Java? Comparable is used to provide natural ordering of objects of a class. Comparator provides custom ordering and added flexibility of sorting objects.

50. Explain different ways to iterate over a collection in Java? Iterating collections can be done through Iterator, for-each loop, forEach(), forEachRemaining() and ListIterator. Iterator allows removing elements during iteration while ListIterator can iterate in reverse.

30 scenarios based interview questions and answers

1. How will you find if a string contains only digits in Java? I can use matches() method of string to match the given string against a regular expression that matches digits like below:

String str = “123”; boolean result = str.matches(“[0-9]+”);

2. How can you swap two numbers without using a temporary variable in Java? We can use arithmetic operators to swap two numbers:

int a = 5; int b = 10;

a = a + b; b = a – b; a = a – b;

3. How can you reverse a string in Java without using any library method? We can write a for loop which starts from the end of the string and appends each character to form the reverse string.

StringBuilder reversed = new StringBuilder();

for(int i = str.length()-1; i >= 0 ; i–){ reversed.append(str.charAt(i)); }

4. How can you find duplicate elements in an array in Java? Iterate through array and store elements as key in a HashMap. If element is already present, print it as duplicate. Time complexity is O(n) and space is O(n).

5. How can you find the largest and smallest number in an unsorted integer array in Java? Iterate through array keeping track of min and max element so far. Time complexity is O(n) to traverse array once.

6. How can you remove duplicates from an array without using any library in Java? Add elements to HashSet which lets only unique elements. Then add set back to array. Time complexity is O(n).

7. How can you find the factorial of a number in Java? Factorial can be calculated using recursion. Base case is f(0) = f(1) = 1. General case is f(n) = n * f(n-1).

8. How can you check if two string are anagrams in Java? 1. Check if length is same 2. Convert strings to char array 3. Sort the char arrays 4. Check if both arrays are equal

9. How can you design a vending machine in Java? Vending machine would have attributes like currentQuantity, pricePerItem. Methods like insertMoney(), selectItem(), dispenseItem(), giveChange() which implement the vending logic.

10. How can you check if a string contains only alphabets in Java? Use matches() with regex “[a-zA-Z]+” to check if string has only alphabets.

11. How can you find whether a year is leap year or not in Java? If year is divisible by 4 and not 100, or divisible by 400, then it is a leap year.

if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) System.out.println(“Leap year”); else System.out.println(“Not a leap year”);

12. How can you swap two Strings without using a temporary variable? We can use StringBuilder’s append() method to swap strings.

string1 = string1.concat(string2); string2 = string1.substring(0, string1.length()-string2.length()); string1 = string1.substring(string2.length());

13. How can you find the middle element of a linked list in Java? – Iterate through linked list to find total length – Traverse till length/2 to find middle element

14. How can you reverse a linked list iteratively and recursively?

1. Initialize prev, current and next 2. In loop, make next = current.next, current.next = prev, prev = current

1. Base case: head or head.next is null 2. Recursively call reverse() on head.next 3. Attach head to the end of reversed list

15. How can you find if a linked list contains a cycle in Java? Use two pointers – fast that moves 2 nodes ahead and slow that moves 1 node. If cycle exists, fast and slow will meet at some node.

16. How can you implement a stack using array and linked list?

Array: Use array, top pointer and push(), pop() operations. Linked List: Use linked list node with next pointer. top pointer and push(), pop() operations.

17. How can you implement a queue using array in Java? Use array, front and rear index, enqueue() and dequeue() operations. Handle queue full and empty conditions.

18. How can you find all permutations of a String in Java? Use recursion. For each char, fix it and find permutations of remaining chars. Add fixed char to beginning and append permutations.

19. How can you design a parking lot using OOPS in Java? ParkingLot class has attributes like totalSpots, availableSpots. Car class has regNo, color etc. Entry and Exit classes manage parkings. Use ArrayList to store parked cars.

20. How can you implement autoboxing and unboxing in your own classes? Autoboxing: Have constructors that take primitive types. Unboxing: Provide get methods that return primitives.

21. How can you find the length of a linked list iteratively and recursively?

Iterative: Initialize length to 0. Traverse linked list and increment length.

Recursive: Length(head) if head == null return 0 else return 1 + length(head.next)

22. How can you find the height of a binary tree in Java? Recursively calculate height of left and right subtrees. Height is max of left height and right height plus 1 for root.

23. How is Bubble Sort algorithm implemented in Java? Compare adjacent elements, swap if currentElement > nextElement. Largest element bubbles up towards end. Repeat until sorted.

24. How can you search for an element in a binary search tree in Java? Start from root and traverse left if element is less than current node otherwise right. Return node if matching element is found.

25. How is Inheritance implemented in Java? Using extends keyword. Single inheritance is supported. Child class inherits properties and methods except private from Parent.

26. How will you implement thread synchronization in Java? 1. Using synchronized keyword 2. Using concurrent collections 3. Using Lock interface 4. Using atomic classes from java.util.concurrent.atomic package

27. How can you avoid deadlock in Java? – Avoid nested locks – Using lock ordering – Using lock timeouts – Avoiding resource sharing between threads

28. How will you store different data types in ArrayList? ArrayList can store only objects. Primitive data types need to be converted to object wrappers like Integer, Character etc.

29. How can you improve performance of ArrayList in Java? Initialise ArrayList with optimal initial capacity to avoid resizing. Use ensureCapacity() before adding large elements to avoid reindexing.

30. How will you implement a HashMap in Java? Use array of LinkedList for chaining. Compute index using hashCode() and compress to fit array. Handle collisions through linked list chaining.

Preparing a strong set of Java interview questions is crucial for aspiring Java developers to successfully clear the technical screening rounds. This collection of 50 Java theory questions and 30 practical scenario-based questions covers a wide range of topics and concepts typically assessed in Java interviews.

Learning the fundamentals and practicing these questions will help candidates master Java programming principles and be able to write code to solve problems. The sample answers provided illustrate how to structure and present your solutions to interviewers to best highlight your Java skills. With thorough preparation on these aspects, developers can confidently tackle Java interview questions and excel in their tech job interviews.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

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..

java interview case study

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.

Crack the top 40 Java coding interview questions

Java coding interview questions

Hiring a Core Java developer can be tricky if you aren’t an experienced developer yourself, as you must effectively analyze candidates’ soft and hard skills and consider whether their experience level matches your expectations.

With a Java skill test and related programming skills tests, you can evaluate multiple skills with minimal stress and effort. All that’s required is for you to invite candidates to complete an assessment.

If you’re having problems building your Core Java interview questions list, there’s no need to worry. Here are 49 questions you can ask experienced candidates to evaluate their abilities and knowledge.

Table of contents

19 core java interview questions for experienced talent about technical knowledge, 5 core java interview questions for experienced programmers with sample answers, 10 core java interview questions for experienced talent about technical processes, 5 technical core java interview questions for experienced talent with sample answers, 10 core java interview questions for experienced talent about operators, 5 operator-related core java interview questions for experienced talent and sample answers, 10 skill-related core java interview questions for experienced programmers, 5 skill-related core java interview questions for experienced talent with sample answers, when should you use core java interview questions for experienced talent, hire skilled programmers using core java interview questions for experienced talent.

For the technical part of the interview, these 19 Core Java interview questions for experienced talent are ideal for testing their knowledge. Ask them some of these questions to assess your candidates’ expertise.

1. Could you explain why inheritance isn’t as beneficial as composition?

2. What do you understand about the term composition?

3. What do you understand about the term aggregation?

4. Could you tell us how composition is different from aggregation?

5. Do you know what a constructor is in Core Java?

6. Could you tell us how many constructors exist in Core Java?

7. What do you understand about default constructors?

8. Can you tell us whether constructors are inherited? Explain your answer.

9. Can programs exceed a memory limit even if they have a garbage collector?

10. What do you know about synchronization? Can you tell us why it’s necessary?

11. Do you know what the varargs feature is? Which symbol would you use for this?

12. Name one advantage of using an ordered array in Core Java.

13. Name one disadvantage of using an ordered array in Core Java.

14. Have you used marker interfaces in your projects? Can you explain what they are?

15. What do you know about double brace initialization in Core Java?

16. Could you tell us how to make an object garbage-collection eligible?

17. Can you name a few examples of Java design pattern categories?

18. How have your soft skills helped you complete Core Java programming duties?

19. Is it true that the length() method in the String class doesn’t provide accurate results?

When reviewing your candidates’ technical interview question responses, have these sample answers ready so you can quickly check the depth of their knowledge.

1. How have your soft skills helped you complete Core Java programming responsibilities?

Java developers should have hard and soft skills to complete Core Java programming responsibilities. Although technical skills may seem more important, soft skills such as time management, communication, and motivation are equally crucial, helping applicants to:

Efficiently prioritize tasks and projects

Take feedback on board

Stay productive when completing tasks

For example, developers must be motivated and organized when developing an application to finish the work within a specific time. Since project delays can harm your company’s relationship with its clients, it’s best to review these soft skills before you hire someone.

But what’s the best way to assess your candidates’ soft skills? It’s easy with our Time Management , Communication , and Motivation skill tests . Use them to check who among your candidates has these abilities.

2. Could you tell us why inheritance isn’t as beneficial as composition?

Senior applicants will know why inheritance is less beneficial than composition in Core Java and respond based on their experience. 

Candidates should know that Core Java doesn’t allow multiple inheritances and that composition is ideal for preventing encapsulation breakage.

Candidates might have a couple of other insights when responding to this question. 

They may mention that composition’s loosely coupled nature is more advantageous than inheritance’s tightly coupled state and that developers can complete unit testing with composition – which isn’t possible with inheritance.

3. Can programs exceed a memory limit even with a garbage collector?

The simple answer to this question is that programs can run out of memory despite having a garbage collector. However, applicants can provide more detail. They should explain that although the garbage collector eliminates objects the program doesn’t require, some might remain in the scope.

Since a few objects may still exist, they can consume memory, which requires developers to dereference objects when they have completed their work.

4. What do you know about synchronization? Can you tell us why it’s necessary?

Synchronization is a process that makes concurrent process execution possible in Java. It’s particularly useful when several threads share one resource. 

Listen out for responses that elaborate on the advantage of synchronization and explain that the process facilitates reliable communication from one thread to another.

5. Do you understand what the varargs feature is? Which symbol would you use for this?

To show their knowledge of Core Java’s essential features, candidates should know that varargs mean variable arguments. But to provide more information, they might explain that engineers introduced the feature in Java 5, which enables developers to:

Assign multiple arguments

Support parameters of one type

Skilled and experienced candidates should explain that the ellipsis symbol […] represents the varargs feature.

Processes and methods for coding an application in Core Java are fundamental – assess your applicants’ knowledge of some essential technical techniques and strategies with some of these questions.

1. How would you print messages on the console? Which method would you use?

2. Which method should developers use to complete dependency injection?

3. Which method would you use to set up the spring bean scope?

4. Is it possible to release a lock on a thread with the sleep() method? 

5. How different is creating a string with new() from forming a literal one?

6. Can you tell us if making a constructor final is possible? Explain your answer.

7. How much do you know about the Java thread lifecycle? Name each step.

8. Do you understand what a memory leak means? Can you tell us what causes it?

9. Can developers import the same package two times in Java?

10. Can developers import only the main package if it has several sub-packages?

Here are five sample answers to the Core Java interview questions about technical processes to help you review your candidates’ knowledge.

1. Which method should developers use to complete dependency injection?

Although there’s no obligatory way to complete dependency injection, there is a recommended method. Candidates should know that developers should use setters if they’re completing optional dependency injection and constructor arguments for mandatory injection.

Knowing why these methods are recommended is important – check if candidates can explain this. For example, they might know that constructors make injecting values into immutable fields easy and enable the program to read them more easily.

2. Which method would you use to set up the spring bean scope?

One of the straightforward ways to set up the spring bean scope is to use a specific annotation or attribute. Applicants with advanced knowledge can specify that the @Scope annotation or attribute can facilitate this process, giving developers more control over bean instances creation.

If your applicants are eager to impress, they will explain that developers can use the annotation and attributes in XML configuration files.

3. Do you understand what a memory leak means? Can you tell us what causes it?

Although this question is similar to the Core Java interview question about garbage collection, applicants should be able to add more detail when responding. 

A memory leak happens when the garbage collector cannot remove – and the system cannot reference –  unused objects. If the garbage collector doesn’t free this memory, this creates a memory leak. 

However, a few other memory leak causes exist, such as:

Unbounded caches

Too much page swapping

Failure to delete custom objects before inserting them

Using the garbage collector correctly is crucial, as it can run 17% slower with three times as much memory. Check if your candidates understand the link between memory and garbage collectors to ensure their applications run efficiently.

4. How much do you know about the Java thread lifecycle? Name each stage.

If your candidates have a deep, technical understanding of the Java thread lifecycle, they may be ideal for a second interview process . Their answer should mention that there are five stages in the process, including:

Five stages of the java thread lifecycle graphic

New : at this stage, developers have not invoked the start() method but have created the thread.

Runnable : this stage occurs after the developer invokes the start() method but before the Java virtual machine invokes the run() method

Running : at this stage, the Java virtual machine invokes the run() method, and the thread begins to execute

Non-Runnable : this stage occurs when the thread cannot run when it is blocked or in a waiting state

Terminated: at this stage, the Java virtual machine has completed the run() method execution

5. Can developers import the same package two times in Java?

Although developers can import the same package twice, the action is usually redundant. Candidates should know that the Java virtual machine typically loads packages and classes once, no matter how many times they import them. So even though this process won’t cause any problems, it can waste time. 

If you want to discover more about your applicants’ operator knowledge, ask them a few of these 10 Core Java interview questions for experienced talent.

1. Do you understand how the >>> operator is different from the >> operator?

2. Could you explain the new() operator’s function in Java?

3. Could you explain the newInstance() operator’s function in Java?

4. Do you know how Java’s new() and newInstance() operators differ?

5. Can you explain how the equals() method differs from the equality operator?

6. Can you explain what a unary operator is in Java?

7. What does the ! operator mean in Core Java?

8. What does the != operator mean in Core Java?

9. What does the ?: operator mean in Core Java?

10. Can you explain what a conditional operator is in Java?

To review your candidates’ operator-related responses, check the sample answers to these five fundamental Core Java interview questions for experienced talent.

The key to assessing responses to this Core Java interview question is to consider if applicants can provide one main difference between the two operators. 

Candidates should know that >> is a bitwise right shift operator that moves each bit to the right and retains the signed bit. They should then explain that >>> is a bitwise right shift operator that provides a trailing zero.

Adding more details to their response will help candidates prove their expertise. If applicants know that the >>> operator does not retain the signed bit, they likely have a good knowledge of operators in Core Java.

2. Could you explain what the new() operator’s function is in Java?

Developers use the new() operator to create objects in Java. It works through class instantiation, helping programmers to allocate memory for new objects. The operator also returns a specific reference to the allocated memory.

If you want to assess your candidates’ knowledge more deeply, ask them questions to see if they know how the new() operator relates to the object constructor. They should know that this operator functions by invoking the constructor. 

What’s important when assessing your applicants’ responses to this question is to check if they know when developers should use the newInstance() operator. Expert programmers will know this operator is ideal when developers don’t know the class name required to create an object. 

They’ll also understand that it functions well when developers need to retrieve the class name from a database, file, or command line argument.

4. Do you know how Java’s new() and newInstance() operators are different?

Even though the new() and newInstance() operators create objects, one key difference exists between them. Developers should use the new() operator if they already know the name of the class when creating the object and the newInstance() operator when they don’t.

Give top marks to candidates who understand that newInstance() is a dynamic method that can help developers load classes from remote sources.

Applicants should know that the equals() method enables developers to compare two objects based on the content of those objects. They should then explain that the equality operator in Java helps developers compare primitive types of data and objects based on their memory location.

If they want to provide more detail, candidates will mention that the equality operator also checks if the two objects point to the same memory locations. 

Core Java skills are critical for Core Java developers. Ensure you review their abilities by asking them some of these 10 Core Java interview questions for experienced programmers.

1. Do you have a good knowledge of object-oriented programming?

2. Why are Java skills important for Core Java developers?

3. Tell us about your application programming interface knowledge.

4. How are Spring Boot skills linked to Core Java? Why are they important?

5. Do you understand what the Java virtual machine is?

6. Explain how good communication helps developers collaborate on projects.

7. Why is problem-solving a fundamental skill for Java developers?

8. Why are critical-thinking skills crucial for Core Java developers?

9. Do you understand why attention to detail is crucial for Core Java developers?

10. Are you familiar with DevOps? Why are DevOps skills necessary for Core Java developers?

Check out the answers to these five skill-related Core Java interview questions to review your candidates’ responses and quickly assess their abilities.

1. Are you familiar with DevOps? Why are DevOps skills necessary for Core Java developers?

Applicants should know that the DevOps model enables teams to implement development, testing, deployment, and application operation. With sufficient DevOps skills, applicants can easily complete continuous integration, Java development automation, and quick feedback implementation. 

Looking for a quick method to assess your interviewees’ DevOps skills before the interview? Use our DevOps skill test to review four essential DevOps subskills.

2. How are Spring Boot skills linked to Core Java? Why are they important?

The great thing about Spring Boot skills is that they facilitate the web application and microservices development process for Java developers. Programmers with this skill can use this open-source framework without integrating special tools. With the right skills, they can use any text editor or integrated development environment to complete their projects.

Therefore, it’s a good idea to assess your candidates’ Spring Boot knowledge with a data-driven skill test, such as our Spring test . This process will help you learn if their abilities are ideal for your company. 

3. Why is problem-solving a fundamental skill for Java developers?

The entire development lifecycle relies on problem-solving skills, which developers should hone for their projects. It’s a critical skill because developers must notice problems and develop strategies to solve issues before delivering software or applications.

After code reviews and software testing, developers must also make changes to the code in line with the feedback, which problem-solving can help with. 63% of developers spend 30 minutes working on projects that require problem-solving, but it’s still vital to assess their abilities and determine if they match your role.

With this in mind, it’s worth asking candidates to complete a Problem Solving skill test before you hire someone to evaluate this essential skill. Our test will reveal the programmers with the most advanced problem-solving skills and experience.

4. Why are critical-thinking skills crucial for Core Java developers?

With critical-thinking skills, Core Java developers can think of unique and viable strategies to handle errors. Without it, they will struggle to select the best methods to resolve problems in their code or application.

For instance, if testing reveals a bug that affects the user experience, candidates can solve this using critical-thinking skills and make the user experience smoother.

Many applicants might complete hackathons or work on projects to develop their critical-thinking skills, but if you need a more quantitative way to assess this, use our Critical Thinking skill test .  

5. Do you understand why attention to detail is crucial for Core Java developers?

Attention to detail is vital for most tasks Core Java developers complete. It can help programmers notice the tiniest errors in their code, which would otherwise ruin the entire program. 

This skill also has other positive consequences for software development. It ensures systems can read and understand the code thanks to the correct syntax and makes code modification easier.

One way to assess applicants’ attention to detail is to use our Attention to Detail test . Integrate it into your candidates’ Core Java assessment for easy candidate evaluation.

You’ve now got a list of interview questions, but it’s important to consider when to use them during the hiring process – which should happen after candidates complete assessments. 

You can remove unskilled candidates immediately based on their lack of skills when you ask applicants to complete the five tests in your assessment.

With this strategy, no unsuitable candidates will enter the interview stage, saving you time, effort, and extra administration work. And combined, these methods give you statistical and qualitative information to help you assess candidates thoroughly.

There isn’t an easier way to assess applicants than to use Core Java interview questions for experienced talent and skill testing, which is why we recommend this easy strategy.

The optimum thing about these methods is the time you’ll save by avoiding resume screening methods because skill testing is the perfect replacement for resume screening.

But what are your next actions? We suggest you sign up to TestGorilla for free or register for a demonstration to learn more about custom questions, branding, and the best way to send candidates invitations.

TestGorilla is making hiring easy for companies like Sony and Revolut. Find out more about it at TestGorilla.

Related posts

Could AI lead to the rise of mediocre employees and mediocre work featured image

Could AI lead to the rise of mediocre employees and mediocre work?

50 Jenkins interview questions featured image

50 Jenkins interview questions to hire top developers

How to hire a squarespace designer featured image

How to hire a squarespace designer (And mistakes to avoid)

Hire the best candidates with TestGorilla

Create pre-employment assessments in minutes to screen candidates, save time, and hire the best talent.

java interview case study

Latest posts

55 Java 8 interview questions featured image

The best advice in pre-employment testing, in your inbox.

No spam. Unsubscribe at any time.

Hire the best. No bias. No stress.

Our screening tests identify the best candidates and make your hiring decisions faster, easier, and bias-free.

Free resources

java interview case study

This checklist covers key features you should look for when choosing a skills testing platform

java interview case study

This resource will help you develop an onboarding checklist for new hires.

java interview case study

How to assess your candidates' attention to detail.

java interview case study

Learn how to get human resources certified through HRCI or SHRM.

java interview case study

Learn how you can improve the level of talent at your company.

java interview case study

Learn how CapitalT reduced hiring bias with online skills assessments.

java interview case study

Learn how to make the resume process more efficient and more effective.

Recruiting metrics

Improve your hiring strategy with these 7 critical recruitment metrics.

java interview case study

Learn how Sukhi decreased time spent reviewing resumes by 83%!

java interview case study

Hire more efficiently with these hacks that 99% of recruiters aren't using.

java interview case study

Make a business case for diversity and inclusion initiatives with this data.

Download Interview guide PDF

  • Java Interview Questions

Download PDF

Do you have what it takes to ace a Java Interview? We are here to help you in consolidating your knowledge and concepts in Java . Before we begin, let's understand what Java is all about.

What is Java? 

Java is a high-level programming language that was developed by James Gosling in the year 1982. It is based on the principles of object-oriented programming and can be used to develop large-scale applications. 

The following article will cover all the popular Core Java interview questions, String Handling interview questions, Java 8 interview questions, Java multithreading interview questions, Java OOPs interview questions, Java exception handling interview questions, collections interview questions, and some frequently asked Java coding interview questions.

Go through all the important questions to enhance your chances of performing well in the Java Interviews. The questions will revolve around the basic, core & advanced fundamentals of Java.

So, let’s dive deep into the plethora of useful Java Technical Interview Questions and Answers categorised into the following sections:

  • Java interview questions for Freshers

Java Intermediate Interview Questions

Java interview questions for experienced, java programming interview questions.

Join our community and share your recent Java interview experiences.

Java Interview Questions for Freshers

1. why is java a platform independent language.

Java language was developed so that it does not depend on any hardware or software because the compiler compiles the code and then converts it to platform-independent byte code which can be run on multiple systems.

  • The only condition to run that byte code is for the machine to have a runtime environment (JRE) installed in it.

2. Why is Java not a pure object oriented language?

Java supports primitive data types - byte, boolean, char, short, int, float, long, and double and hence it is not a pure object oriented language .

3. Difference between Heap and Stack Memory in java. And how java utilizes this.

Stack memory is the portion of memory that was assigned to every individual program. And it was fixed. On the other hand, Heap memory is the portion that was not allocated to the java program but it will be available for use by the java program when it is required, mostly during the runtime of the program.

Java Utilizes this memory as - 

  • When we write a java program then all the variables, methods, etc are stored in the stack memory.
  • And when we create any object in the java program then that object was created in the heap memory. And it was referenced from the stack memory.

Example- Consider the below java program :

For this java program. The stack and heap memory occupied by java is -

java interview case study

Main and PrintArray is the method that will be available in the stack area and as well as the variables declared that will also be in the stack area. 

And the Object (Integer Array of size 10) we have created, will be available in the Heap area because that space will be allocated to the program during runtime. 

4. Can java be said to be the complete object-oriented programming language?

It is not wrong if we claim that Java is the complete object-oriented programming language because everything in Java is under the classes and we can access them by creating the objects.

But we can even say that Java is not a completely object-oriented programming language because it has the support of primitive data types like int, float, char, boolean, double, etc.

Now for the question: Is Java a completely object-oriented programming language? We can say that - Java is not a pure object-oriented programming language, because it has direct access to primitive data types. And these primitive data types don't directly belong to the Integer classes.

5. How is Java different from C++?

  • C++ is only a  compiled language, whereas Java is compiled as well as an interpreted language.
  • Java programs are machine-independent whereas a c++ program can run only in the machine in which it is compiled. 
  • C++ allows users to use pointers in the program. Whereas java doesn’t allow it. Java internally uses pointers. 
  • C++ supports the concept of Multiple inheritances whereas Java doesn't support this. And it is due to avoiding the complexity of name ambiguity that causes the diamond problem.

Learn via our Video Courses

6. pointers are used in c/ c++. why does java not make use of pointers.

Pointers are quite complicated and unsafe to use by beginner programmers. Java focuses on code simplicity, and the usage of pointers can make it challenging. Pointer utilization can also cause potential errors. Moreover, security is also compromised if pointers are used because the users can directly access memory with the help of pointers.

Thus, a certain level of abstraction is furnished by not including pointers in Java. Moreover, the usage of pointers can make the procedure of garbage collection quite slow and erroneous. Java makes use of references as these cannot be manipulated, unlike pointers.

7. What do you understand by an instance variable and a local variable?

Instance variables are those variables that are accessible by all the methods in the class. They are declared outside the methods and inside the class. These variables describe the properties of an object and remain bound to it at any cost.

All the objects of the class will have their copy of the variables for utilization. If any modification is done on these variables, then only that instance will be impacted by it, and all other class instances continue to remain unaffected.

Local variables are those variables present within a block, function, or constructor and can be accessed only inside them. The utilization of the variable is restricted to the block scope. Whenever a local variable is declared inside a method, the other class methods don’t have any knowledge about the local variable.

java interview case study

8. What are the default values assigned to variables and instances in java?

  • There are no default values assigned to the variables in java. We need to initialize the value before using it. Otherwise, it will throw a compilation error of ( Variable might not be initialized ). 
  • But for instance, if we create the object, then the default value will be initialized by the default constructor depending on the data type. 
  • If it is a reference, then it will be assigned to null. 
  • If it is numeric, then it will assign to 0.
  • If it is a boolean, then it will be assigned to false. Etc.

9. What do you mean by data encapsulation?

  • Data Encapsulation is an Object-Oriented Programming concept of hiding the data attributes and their behaviours in a single unit.
  • It helps developers to follow modularity while developing software by ensuring that each object is independent of other objects by having its own methods, attributes, and functionalities.
  • It is used for the security of the private properties of an object and hence serves the purpose of data hiding.

java interview case study

10. Tell us something about JIT compiler.

  • JIT stands for Just-In-Time and it is used for improving the performance during run time. It does the task of compiling parts of byte code having similar functionality at the same time thereby reducing the amount of compilation time for the code to run.
  • First, the Java source code (.java) conversion to byte code (.class) occurs with the help of the javac compiler.
  • Then, the .class files are loaded at run time by JVM and with the help of an interpreter, these are converted to machine understandable code.
  • JIT compiler is a part of JVM. When the JIT compiler is enabled, the JVM analyzes the method calls in the .class files and compiles them to get more efficient and native code. It also ensures that the prioritized method calls are optimized.
  • Once the above step is done, the JVM executes the optimized code directly instead of interpreting the code again. This increases the performance and speed of the execution.

java interview case study

11. Can you tell the difference between equals() method and equality operator (==) in Java?

We are already aware of the (==) equals operator. That we have used this to compare the equality of the values. But when we talk about the terms of object-oriented programming, we deal with the values in the form of objects. And this object may contain multiple types of data. So using the (==) operator does not work in this case. So we need to go with the . equals() method.

Both [(==) and .equals()] primary functionalities are to compare the values, but the secondary functionality is different. 

So in order to understand this better, let’s consider this with the example -

This code will print true. We know that both strings are equals so it will print true. But here (==) Operators don’t compare each character in this case. It compares the memory location. And because the string uses the constant pool for storing the values in the memory, both str1 and str2 are stored at the same memory location. See the detailed Explanation in Question no 73: Link .

java interview case study

Now, if we modify the program a little bit with -

java interview case study

Then in this case, it will print false. Because here no longer the constant pool concepts are used. Here, new memory is allocated. So here the memory address is different, therefore ( == ) Operator returns false. But the twist is that the values are the same in both strings. So how to compare the values? Here the .equals() method is used.

.equals() method compares the values and returns the result accordingly.  If we modify the above code with - 

Then it returns true.

  • In the cases where the equals method is not overridden in a class, then the class uses the default implementation of the equals method that is closest to the parent class.
  • Object class is considered as the parent class of all the java classes. The implementation of the equals method in the Object class uses the == operator to compare two objects. This default implementation can be overridden as per the business logic.

12. How is an infinite loop declared in Java?

Infinite loops are those loops that run infinitely without any breaking conditions. Some examples of consciously declaring infinite loop is:

  • Using For Loop:
  • Using while loop:
  • Using do-while loop:

13. Briefly explain the concept of constructor overloading

Constructor overloading is the process of creating multiple constructors in the class consisting of the same name with a difference in the constructor parameters. Depending upon the number of parameters and their corresponding types, distinguishing of the different types of constructors is done by the compiler.

java interview case study

Three constructors are defined here but they differ on the basis of parameter type and their numbers.

14. Define Copy constructor in java.

Copy Constructor is the constructor used when we want to initialize the value to the new object from the old object of the same class. 

Here we are initializing the new object value from the old object value in the constructor. Although, this can also be achieved with the help of object cloning.

15. Can the main method be Overloaded?

Yes, It is possible to overload the main method. We can create as many overloaded main methods we want. However, JVM has a predefined calling method that JVM will only call the main method with the definition of - 

Consider the below code snippets: 

16. Comment on method overloading and overriding by citing relevant examples.

In Java, method overloading is made possible by introducing different methods in the same class consisting of the same name. Still, all the functions differ in the number or type of parameters. It takes place inside a class and enhances program readability.

The only difference in the return type of the method does not promote method overloading. The following example will furnish you with a clear picture of it.

java interview case study

Both the functions have the same name but differ in the number of arguments. The first method calculates the area of the rectangle, whereas the second method calculates the area of a cuboid.

Method overriding is the concept in which two methods having the same method signature are present in two different classes in which an inheritance relationship is present. A particular method implementation (already present in the base class) is possible for the derived class by using method overriding. Let’s give a look at this example:

java interview case study

Both class methods have the name walk and the same parameters, distance, and time. If the derived class method is called, then the base class method walk gets overridden by that of the derived class.

17. A single try block and multiple catch blocks can co-exist in a Java Program. Explain.

Yes, multiple catch blocks can exist but specific approaches should come prior to the general approach because only the first catch block satisfying the catch condition is executed. The given code illustrates the same:

Here, the second catch block will be executed because of division by 0 (i / x). In case x was greater than 0 then the first catch block will execute because for loop runs till i = n and array index are till n-1.

18. Explain the use of final keyword in variable, method and class.

In Java, the final keyword is used as defining something as constant /final and represents the non-access modifier.

  • When a variable is declared as final in Java, the value can’t be modified once it has been assigned.
  • If any value has not been assigned to that variable, then it can be assigned only by the constructor of the class.
  • A method declared as final cannot be overridden by its children's classes.
  • A constructor cannot be marked as final because whenever a class is inherited, the constructors are not inherited. Hence, marking it final doesn't make sense. Java throws compilation error saying - modifier final not allowed here
  • No classes can be inherited from the class declared as final. But that final class can extend other classes for its usage.

19. Do final, finally and finalize keywords have the same function?

All three keywords have their own utility while programming.

Final: If any restriction is required for classes, variables, or methods, the final keyword comes in handy. Inheritance of a final class and overriding of a final method is restricted by the use of the final keyword. The variable value becomes fixed after incorporating the final keyword. Example:

The second statement will throw an error.

Finally: It is the block present in a program where all the codes written inside it get executed irrespective of handling of exceptions. Example:

Finalize: Prior to the garbage collection of an object, the finalize method is called so that the clean-up activity is implemented. Example:

20. Is it possible that the ‘finally’ block will not be executed? If yes then list the case.

 Yes. It is possible that the ‘finally’ block will not be executed. The cases are-

  • Suppose we use System.exit() in the above statement.
  • If there are fatal errors like Stack overflow, Memory access error, etc.

21. Identify the output of the java program and state the reason.

The above code will generate a compile-time error at Line 7 saying - [error: variable i might already have been initialized] . It is because variable ‘i’ is the final variable. And final variables are allowed to be initialized only once, and that was already done on line no 5.

22. When can you use super keyword?

  • The super keyword is used to access hidden fields and overridden methods or attributes of the parent class.
  • Accessing data members of parent class when the member names of the class and its child subclasses are same.
  • To call the default and parameterized constructor of the parent class inside the child class.
  • Accessing the parent class methods when the child classes have overridden them.
  • The following example demonstrates all 3 cases when a super keyword is used.

23. Can the static methods be overloaded?

Yes! There can be two or more static methods in a class with the same name but differing input parameters.

24. Why is the main method static in Java?

The main method is always static because static members are those methods that belong to the classes, not to an individual object. So if the main method will not be static then for every object, It is available. And that is not acceptable by JVM. JVM calls the main method based on the class name itself. Not by creating the object.

Because there must be only 1 main method in the java program as the execution starts from the main method. So for this reason the main method is static. 

25. Can the static methods be overridden?

  • No! Declaration of static methods having the same signature can be done in the subclass but run time polymorphism can not take place in such cases.
  • Overriding or dynamic polymorphism occurs during the runtime, but the static methods are loaded and looked up at the compile time statically. Hence, these methods cant be overridden.

26. Difference between static methods, static variables, and static classes in java.

  • For example - We have used mathematical functions in the java program like - max(), min(), sqrt(), pow(), etc. And if we notice that, then we will find that we call it directly with the class name. Like - Math.max(), Math.min(), etc. So that is a static method.  And Similarly static variables we have used like (length) for the array to get the length. So that is the static method.
  • Static classes - A class in the java program cannot be static except if it is the inner class. If it is an inner static class, then it exactly works like other static members of the class.

27. What is the main objective of garbage collection?

The main objective of this process is to free up the memory space occupied by the unnecessary and unreachable objects during the Java program execution by deleting those unreachable objects.

  • This ensures that the memory resource is used efficiently, but it provides no guarantee that there would be sufficient memory for the program execution.

28. What is a ClassLoader?

  • Java Classloader is the program that belongs to JRE (Java Runtime Environment). The task of ClassLoader is to load the required classes and interfaces to the JVM when required. 
  • Example- To get input from the console, we require the scanner class. And the Scanner class is loaded by the ClassLoader.

29. What part of memory - Stack or Heap - is cleaned in garbage collection process?

30. what are shallow copy and deep copy in java.

To copy the object's data, we have several methods like deep copy and shallow copy. 

Object for this Rectangle class - Rectangle obj1 = new Rectangle();

  • Shallow copy - The shallow copy only creates a new reference and points to the same object. Example - For Shallow copy, we can do this by -

Now by doing this what will happen is the new reference is created with the name obj2 and that will point to the same memory location.

  • Deep Copy - In a deep copy, we create a new object and copy the old object value to the new object. Example -

Both these objects will point to the memory location as stated below -

java interview case study

Now, if we change the values in shallow copy then they affect the other reference as well. Let's see with the help of an example - 

We can see that in the above code, if we change the values of object1, then the object2 values also get changed. It is because of the reference.

Now, if we change the code to deep copy, then there will be no effect on object2 if it is of type deep copy. Consider some snippets to be added in the above code.

The above snippet will not affect the object2 values. It has its separate values. The output will be

Now we see that we need to write the number of codes for this deep copy. So to reduce this, In java, there is a method called clone().  

The clone() will do this deep copy internally and return a new object. And to do this we need to write only 1 line of code. That is - Rectangle obj2 = obj1.clone();

1. Apart from the security aspect, what are the reasons behind making strings immutable in Java?

A String is made immutable due to the following reasons:

  • String Pool: Designers of Java were aware of the fact that String data type is going to be majorly used by the programmers and developers. Thus, they wanted optimization from the beginning. They came up with the notion of using the String pool (a storage area in Java heap) to store the String literals. They intended to decrease the temporary String object with the help of sharing. An immutable class is needed to facilitate sharing. The sharing of the mutable structures between two unknown parties is not possible. Thus, immutable Java String helps in executing the concept of String Pool.

java interview case study

  • Multithreading : The safety of threads regarding the String objects is an important aspect in Java. No external synchronization is required if the String objects are immutable. Thus, a cleaner code can be written for sharing the String objects across different threads. The complex process of concurrency is facilitated by this method.
  • Collections : In the case of Hashtables and HashMaps, keys are String objects. If the String objects are not immutable, then it can get modified during the period when it resides in the HashMaps. Consequently, the retrieval of the desired data is not possible. Such changing states pose a lot of risks. Therefore, it is quite safe to make the string immutable.

2. What is a singleton class in Java? And How to implement a singleton class?

Singleton classes are those classes, whose objects are created only once. And with only that object the class members can be accessed. 

Understand this with the help of an example-:

Consider the water jug in the office and if every employee wants that water then they will not create a new water jug for drinking water. They will use the existing one with their own reference as a glass. So programmatically it should be implemented as -

In the above class, the Constructor is private so we cannot create the object of the class. But we can get the object by calling the method getInstance() . And the getInstance is static so it can be called without creating the object. And it returns the object. Now with that object, we can call getWater() to get the water.

We can get the single object using this getInstance(). And it is static, so it is a thread-safe singleton class. Although there are many ways to create a thread-safe singleton class. So thread-safe classes can also be:

  • When singletons are written with double-checked locking, they can be thread-safe.
  • We can use static singletons that are initialized during class loading. Like we did in the above example.
  • But the most straightforward way to create a thread-safe singleton is to use Java enums.

3. Which of the below generates a compile-time error? State the reason.

  • int[] n1 = new int[0];
  • boolean[] n2 = new boolean[-200];
  • double[] n3 = new double[2241423798];
  • char[] ch = new char[20];

We get a compile-time error in line 3. The error we will get in Line 3 is - integer number too large . It is because the array requires size as an integer. And Integer takes 4 Bytes in the memory. And the number ( 2241423798 ) is beyond the capacity of the integer. The maximum array size we can declare is - ( 2147483647 ).

Because the array requires the size in integer, none of the lines (1, 2, and 4) will give a compile-time error. The program will compile fine. But we get the runtime exception in line 2. The exception is - NegativeArraySizeException . 

Here what will happen is - At the time when JVM will allocate the required memory during runtime then it will find that the size is negative. And the array size can’t be negative. So the JVM will throw the exception.

4. How would you differentiate between a String, StringBuffer, and a StringBuilder?

  • Storage area: In string, the String pool serves as the storage area. For StringBuilder and StringBuffer, heap memory is the storage area.
  • Mutability: A String is immutable, whereas both the StringBuilder and StringBuffer are mutable.
  • Efficiency: It is quite slow to work with a String. However, StringBuilder is the fastest in performing operations. The speed of a StringBuffer is more than a String and less than a StringBuilder. (For example appending a character is fastest in StringBuilder and very slow in String because a new memory is required for the new String with appended character.)
  • Thread-safe: In the case of a threaded environment, StringBuilder and StringBuffer are used whereas a String is not used. However, StringBuilder is suitable for an environment with a single thread, and a StringBuffer is suitable for multiple threads. Syntax:

5. Using relevant properties highlight the differences between interfaces and abstract classes.

  • Availability of methods: Only abstract methods are available in interfaces, whereas non-abstract methods can be present along with abstract methods in abstract classes.
  • Variable types : Static and final variables can only be declared in the case of interfaces, whereas abstract classes can also have non-static and non-final variables.
  • Inheritance: Multiple inheritances are facilitated by interfaces, whereas abstract classes do not promote multiple inheritances.
  • Data member accessibility: By default, the class data members of interfaces are of the public- type. Conversely, the class members for an abstract class can be protected or private also.
  • Implementation: With the help of an abstract class, the implementation of an interface is easily possible. However, the converse is not true;

Abstract class example:

Interface example:

6. Is this program giving a compile-time error? If Yes then state the reason and number of errors it will give. If not then state the reason.

The above program will give a compile-time error. The compiler will throw 2 errors in this.

  • [Illegal Combination of modifiers: abstract and final] at line 1.
  • [Cannot inherit from final ‘InterviewBit’] at line 4.

It is because abstract classes are incomplete classes that need to be inherited for making their concrete classes. And on the other hand, the final keywords in class are used for avoiding inheritance. So these combinations are not allowed in java.

7. What is a Comparator in java?

Consider the example where we have an ArrayList of employees like( EId, Ename, Salary), etc. Now if we want to sort this list of employees based on the names of employees. Then that is not possible to sort using the Collections.sort() method. We need to provide something to the sort() function depending on what values we have to perform sorting. Then in that case a comparator is used.

Comparator is the interface in java that contains the compare method. And by overloading the compare method, we can define that on what basis we need to compare the values. 

8. In Java, static as well as private method overriding is possible. Comment on the statement.

The statement in the context is completely False. The static methods have no relevance with the objects, and these methods are of the class level. In the case of a child class, a static method with a method signature exactly like that of the parent class can exist without even throwing any compilation error.

The phenomenon mentioned here is popularly known as method hiding, and overriding is certainly not possible. Private method overriding is unimaginable because the visibility of the private method is restricted to the parent class only. As a result, only hiding can be facilitated and not overriding.

9. What makes a HashSet different from a TreeSet?

Although both HashSet and TreeSet are not synchronized and ensure that duplicates are not present, there are certain properties that distinguish a HashSet from a TreeSet.

  • Implementation: For a HashSet, the hash table is utilized for storing the elements in an unordered manner. However, TreeSet makes use of the red-black tree to store the elements in a sorted manner.
  • Complexity/ Performance: For adding, retrieving, and deleting elements, the time amortized complexity is O(1) for a HashSet. The time complexity for performing the same operations is a bit higher for TreeSet and is equal to O(log n). Overall, the performance of HashSet is faster in comparison to TreeSet.
  • Methods: hashCode() and equals() are the methods utilized by HashSet for making comparisons between the objects. Conversely, compareTo() and compare() methods are utilized by TreeSet to facilitate object comparisons.
  • Objects type: Heterogeneous and null objects can be stored with the help of HashSet. In the case of a TreeSet, runtime exception occurs while inserting heterogeneous objects or null objects.

10. Why is the character array preferred over string for storing confidential information?

In Java, a string is basically immutable i.e. it cannot be modified. After its declaration, it continues to stay in the string pool as long as it is not removed in the form of garbage. In other words, a string resides in the heap section of the memory for an unregulated and unspecified time interval after string value processing is executed.

As a result, vital information can be stolen for pursuing harmful activities by hackers if a memory dump is illegally accessed by them. Such risks can be eliminated by using mutable objects or structures like character arrays for storing any variable. After the work of the character array variable is done, the variable can be configured to blank at the same instant. Consequently, it helps in saving heap memory and also gives no chance to the hackers to extract vital data.

11. What do we get in the JDK file?

  • JDK - For making java programs, we need some tools that are provided by JDK (Java Development Kit). JDK is the package that contains various tools, Compiler, Java Runtime Environment, etc.
  • JRE -  To execute the java program we need an environment. (Java Runtime Environment) JRE contains a library of Java classes +  JVM. What are JAVA Classes?  It contains some predefined methods that help Java programs to use that feature, build and execute. For example - there is a system class in java that contains the print-stream method, and with the help of this, we can print something on the console.
  • JVM - (Java Virtual Machine) JVM  is a part of JRE that executes the Java program at the end.  Actually, it is part of JRE, but it is software that converts bytecode into machine-executable code to execute on hardware.

java interview case study

12. What are the differences between JVM, JRE and JDK in Java?

13. what are the differences between hashmap and hashtable in java, 14. what is the importance of reflection in java.

  • The term reflection is used for describing the inspection capability of a code on other code either of itself or of its system and modify it during runtime.
  • Consider an example where we have an object of unknown type and we have a method ‘fooBar()’ which we need to call on the object. The static typing system of Java doesn't allow this method invocation unless the type of the object is known beforehand. This can be achieved using reflection which allows the code to scan the object and identify if it has any method called “fooBar()” and only then call the method if needed.
  • Speed — Method invocations due to reflection are about three times slower than the direct method calls.
  • Type safety — When a method is invoked via its reference wrongly using reflection, invocation fails at runtime as it is not detected at compile/load time.
  • Traceability — Whenever a reflective method fails, it is very difficult to find the root cause of this failure due to a huge stack trace. One has to deep dive into the invoke() and proxy() method logs to identify the root cause.
  • Hence, it is advisable to follow solutions that don't involve reflection and use this method as a last resort.

15. What are the different ways of threads usage?

  • Extending the Thread class
  • Implementing the Runnable interface
  • Implementing a thread using the method of Runnable interface is more preferred and advantageous as Java does not have support for multiple inheritances of classes.
  • start() method is used for creating a separate call stack for the thread execution. Once the call stack is created, JVM calls the run() method for executing the thread in that call stack.

16. What are the different types of Thread Priorities in Java? And what is the default priority of a thread assigned by JVM?

There are a total of 3 different types of priority available in Java. 

MIN_PRIORITY: It has an integer value assigned with 1. MAX_PRIORITY: It has an integer value assigned with 10. NORM_PRIORITY: It has an integer value assigned with 5.

In Java, Thread with MAX_PRIORITY gets the first chance to execute. But the default priority for any thread is NORM_PRIORITY assigned by JVM. 

17. What is the difference between the program and the process?

  • A program can be defined as a line of code written in order to accomplish a particular task. Whereas the process can be defined as the programs which are under execution. 
  • A program doesn't execute directly by the CPU. First, the resources are allocated to the program and when it is ready for execution then it is a process.

18. What is the difference between the ‘throw’ and ‘throws’ keyword in java?

  • The ‘ throw ’ keyword is used to manually throw the exception to the calling method.
  • And the ‘ throws ’ keyword is used in the function definition to inform the calling method that this method throws the exception. So if you are calling, then you have to handle the exception.

Here in the above snippet, the method testExceptionDivide throws an exception. So if the main method is calling it then it must have handled the exception. Otherwise, the main method can also throw the exception to JVM.

And the method testExceptionDivide 'throws’ the exception based on the condition.

19. What are the differences between constructor and method of a class in Java?

20. identify the output of the below java program and justify your answer..

The above code will throw the compilation error. It is because the super() is used to call the parent class constructor. But there is the condition that super() must be the first statement in the block. Now in this case, if we replace this() with super() then also it will throw the compilation error. Because this() also has to be the first statement in the block. So in conclusion, we can say that we cannot use this() and super() keywords in the same block.

21. Java works as “pass by value” or “pass by reference” phenomenon?

Java always works as a “pass by value”. There is nothing called a “pass by reference” in Java. However, when the object is passed in any method, the address of the value is passed due to the nature of object handling in Java. When an object is passed, a copy of the reference is created by Java and that is passed to the method. The objects point to the same memory location. 2 cases might happen inside the method:

  • Case 1: When the object is pointed to another location: In this case, the changes made to that object do not get reflected the original object before it was passed to the method as the reference points to another location.

For example:

  • Case 2: When object references are not modified: In this case, since we have the copy of reference the main object pointing to the same memory location, any changes in the content of the object get reflected in the original object.

22. What is the ‘IS-A ‘ relationship in OOPs java?

‘IS-A’ relationship is another name for inheritance. When we inherit the base class from the derived class, then it forms a relationship between the classes. So that relationship is termed an ‘IS-A’ Relationship.

Example - Consider a Television (Typical CRT TV). Now another Smart TV  that is inherited from television class. So we can say that the Smart iv is also a TV. Because CRT TV things can also be done in the Smart TV.

java interview case study

So here ‘IS-A’ Relationship formed. [ SmartTV ‘IS-A’ TV ] .

23. Which among String or String Buffer should be preferred when there are lot of updates required to be done in the data?

StringBuffer is mutable and dynamic in nature whereas String is immutable. Every updation / modification of String creates a new String thereby overloading the string pool with unnecessary objects. Hence, in the cases of a lot of updates, it is always preferred to use StringBuffer as it will reduce the overhead of the creation of multiple String objects in the string pool.

24. How to not allow serialization of attributes of a class in Java?

  • In order to achieve this, the attribute can be declared along with the usage of transient keyword as shown below:
  • In the above example, all the fields except someInfo can be serialized.

25. What happens if the static modifier is not included in the main method signature in Java?

There wouldn't be any compilation error. But then the program is run, since the JVM cant map the main method signature, the code throws “NoSuchMethodError” error at the runtime.

26. Consider the below program, identify the output, and also state the reason for that.

The output of the above program will be Hello. Main Method . This is because JVM will always call the main method based on the definition it already has. Doesn't matter how many main methods we overload it will only execute one main method based on its declaration in JVM.

27. Can we make the main() thread a daemon thread?

In java multithreading, the main() threads are always non-daemon threads. And there is no way we can change the nature of the non-daemon thread to the daemon thread.

28. What happens if there are multiple main methods inside one class in Java?

The program can't compile as the compiler says that the method has been already defined inside the class.

29. What do you understand by Object Cloning and how do you achieve it in Java?

  • It is the process of creating an exact copy of any object. In order to support this, a java class has to implement the Cloneable interface of java.lang package and override the clone() method provided by the Object class the syntax of which is:
  • In case the Cloneable interface is not implemented and just the method is overridden, it results in CloneNotSupportedException in Java.

30. How does an exception propagate in the code?

When an exception occurs, first it searches to locate the matching catch block. In case, the matching catch block is located, then that block would be executed. Else, the exception propagates through the method call stack and goes into the caller method where the process of matching the catch block is performed. This propagation happens until the matching catch block is found. If the match is not found, then the program gets terminated in the main method.

java interview case study

31. How do exceptions affect the program if it doesn't handle them?

Exceptions are runtime errors. Suppose we are making an android application with java. And it all works fine but there is an exceptional case when the application tries to get the file from storage and the file doesn’t exist (This is the case of exception in java). And if this case is not handled properly then the application will crash. This will be a bad experience for users.  This is the type of error that cannot be controlled by the programmer. But programmers can take some steps to avoid this so that the application won’t crash. The proper action can be taken at this step.

32. Is it mandatory for a catch block to be followed after a try block?

No, it is not necessary for a catch block to be present after a try block. - A try block should be followed either by a catch block or by a finally block. If the exceptions likelihood is more, then they should be declared using the throws clause of the method.

33. Will the finally block get executed when the return statement is written at the end of try block and catch block as shown below?

finally block will be executed irrespective of the exception or not. The only case where finally block is not executed is when it encounters ‘System.exit()’ method anywhere in try/catch block.

34. Can you call a constructor of a class inside the another constructor?

Yes, the concept can be termed as constructor chaining and can be achieved using this() .

java interview case study

35. Contiguous memory locations are usually used for storing actual values in an array but not in ArrayList. Explain.

In the case of ArrayList, data storing in the form of primitive data types (like int, float, etc.) is not possible. The data members/objects present in the ArrayList have references to the objects which are located at various sites in the memory. Thus, storing of actual objects or non-primitive data types (like Integer, Double, etc.) takes place in various memory locations.

java interview case study

However, the same does not apply to the arrays. Object or primitive type values can be stored in arrays in contiguous memory locations, hence every element does not require any reference to the next element.

java interview case study

36. Why does the java array index start with 0?

It is because the 0 index array avoids the extra arithmetic operation to calculate the memory address.

Example - Consider the array and assume each element takes 4-byte memory space. Then the address will be like this -

java interview case study

Now if we want to access index 4. Then internally java calculates the address using the formula-

[Base Address + (index * no_of_bytes)] . So according to this. The starting address of the index 4 will be - [100 + (4*4)] = 116 . And exactly that's what the address is calculated.  Now consider the same with 1 index Array -

java interview case study

Now if we apply the same formula here. Then we get - 116 as the starting address of the 4th index. Which is wrong. Then we need to apply formula - [ Base Address + ((index-1) * no_of_bytes)] .

And for calculating this, an extra arithmetic operation has to be performed. And consider the case where millions of addresses need to be calculated, this causes complexity. So to avoid this, ) the index array is supported by java.

37. Why is the remove method faster in the linked list than in an array?

In the linked list, we only need to adjust the references when we want to delete the element from either end or the front of the linked list. But in the array, indexes are used. So to manage proper indexing, we need to adjust the values from the array So this adjustment of value is costlier than the adjustment of references.

Example - To Delete from the front of the linked list, internally the references adjustments happened like this.

java interview case study

The only thing that will change is that the head pointer will point to the head’s next node. And delete the previous node. That is the constant time operation.

Whereas in the ArrayList, internally it should work like this-

java interview case study

For deletion of the first element, all the next element has to move to one place ahead. So this copying value takes time. So that is the reason why removing in ArrayList is slower than LinkedList.

38. How many overloaded add() and addAll() methods are available in the List interface? Describe the need and uses.

There are a total of 4 overloaded methods for add() and addAll() methods available in List Interface. The below table states the description of all.

39. How does the size of ArrayList grow dynamically? And also state how it is implemented internally.

ArrayList is implemented in such a way that it can grow dynamically. We don't need to specify the size of ArrayList. For adding the values in it, the methodology it uses is -

1. Consider initially that there are 2 elements in the ArrayList. [2, 3] .

java interview case study

2. If we need to add the element into this. Then internally what will happen is-

  • ArrayList will allocate the new ArrayList of Size (current size + half of the current size). And add the old elements into the new. Old - [2, 3],    New - [2, 3, null].

java interview case study

  • Then the new value will be inserted into it. [2, 3, 4, null]. And for the next time, the extra space will be available for the value to be inserted.

java interview case study

3. This process continues and the time taken to perform all of these is considered as the amortized constant time. 

This is how the ArrayList grows dynamically. And when we delete any entry from the ArrayList then the following steps are performed -

1. It searches for the element index in the array. Searching takes some time. Typically it’s O(n) because it needs to search for the element in the entire array.

java interview case study

2. After searching the element, it needs to shift the element from the right side to fill the index.

java interview case study

So this is how the elements are deleted from the ArrayList internally. Similarly, the search operations are also implemented internally as defined in removing elements from the list (searching for elements to delete).

1. Although inheritance is a popular OOPs concept, it is less advantageous than composition. Explain.

Inheritance lags behind composition in the following scenarios:

  • Multiple-inheritance is not possible in Java. Classes can only extend from one superclass. In cases where multiple functionalities are required, for example - to read and write information into the file, the pattern of composition is preferred. The writer, as well as reader functionalities, can be made use of by considering them as the private members.
  • Composition assists in attaining high flexibility and prevents breaking of encapsulation.
  • Unit testing is possible with composition and not inheritance. When a developer wants to test a class composing a different class, then Mock Object can be created for signifying the composed class to facilitate testing. This technique is not possible with the help of inheritance as the derived class cannot be tested without the help of the superclass in inheritance.
  • The loosely coupled nature of composition is preferable over the tightly coupled nature of inheritance.

Let’s take an example:

In the above example, inheritance is followed. Now, some modifications are done to the Top class like this:

If the new implementation of the Top class is followed, a compile-time error is bound to occur in the Bottom class. Incompatible return type is there for the Top.stop() function. Changes have to be made to either the Top or the Bottom class to ensure compatibility. However, the composition technique can be utilized to solve the given problem:

2. What is the difference between ‘>>’ and ‘>>>’ operators in java?

These 2 are the bitwise right shift operators. Although both operators look similar. But there is a minimal difference between these two right shift operators.

  • ‘>>’ Bitwise Right Shift Operator - This operator shifts each bit to its right position. And this maintains the signed bit.
  • ‘>>>’ Bitwise Right Shift Operator with trailing zero - This operator also shifts each bit to its right. But this doesn’t maintain the signed bit. This operator makes the Most significant bit to 0.

Example- Num1 = 8, Num2 = -8.

So the binary form of these numbers are - 

Num1 = 00000000 00000000 00000000 00001000  Num2 = 11111111 11111111 11111111  11111000

‘>>’ Operator : 8 >> 1 (Shift by one bit) : 

Num1 = 00000000 00000000 00000000 00000100 Num2 = 11111111 11111111 11111111  11111100

‘>>>’ Operator : 8 >>> 1 (Shift by one bit) = 

Num1 = 00000000 00000000 00000000 00000100 Num2 = 01111111 11111111 11111111 11111100

3. What are Composition and Aggregation? State the difference.

Composition, and Aggregation help to build (Has - A - Relationship) between classes and objects. But both are not the same in the end. Let’s understand with the help of an example. 

  • Consider the University as a class that has some departments in it. So the university will be the container object. And departments in it will contain objects. Now in this case, if the container object destroys then the contained objects will also get destroyed automatically.  So here we can say that there is a strong association between the objects. So this Strong Association is called Composition .
  • Now consider one more example. Suppose we have a class department and there are several professors' objects there in the department. Now if the department class is destroyed then the professor's object will become free to bind with other objects. Because container objects (Department) only hold the references of contained objects (Professor’s). So here is the weak association between the objects. And this weak association is called Aggregation .

4. How is the creation of a String using new() different from that of a literal?

When a String is formed as a literal with the assistance of an assignment operator, it makes its way into the String constant pool so that String Interning can take place. This same object in the heap will be referenced by a different String if the content is the same for both of them.

The checking() function will return true as the same content is referenced by both the variables.

java interview case study

Conversely, when a String formation takes place with the help of a new() operator, interning does not take place. The object gets created in the heap memory even if the same content object is present.

The checking() function will return false as the same content is not referenced by both the variables.

java interview case study

5. How is the ‘new’ operator different from the ‘newInstance()’ operator in java?

Both ‘ new ’ and ‘ newInstance() ’ operators are used to creating objects. The difference is- that when we already know the class name for which we have to create the object then we use a new operator. But suppose we don’t know the class name for which we need to create the object, Or we get the class name from the command line argument, or the database, or the file. Then in that case we use the ‘ newInstance() ’ operator.

The ‘ newInstance() ’ keyword throws an exception that we need to handle. It is because there are chances that the class definition doesn’t exist, and we get the class name from runtime. So it will throw an exception.

6. Is exceeding the memory limit possible in a program despite having a garbage collector?

Yes, it is possible for the program to go out of memory in spite of the presence of a garbage collector. Garbage collection assists in recognizing and eliminating those objects which are not required in the program anymore, in order to free up the resources used by them.

In a program, if an object is unreachable, then the execution of garbage collection takes place with respect to that object. If the amount of memory required for creating a new object is not sufficient, then memory is released for those objects which are no longer in the scope with the help of a garbage collector. The memory limit is exceeded for the program when the memory released is not enough for creating new objects.

Moreover, exhaustion of the heap memory takes place if objects are created in such a manner that they remain in the scope and consume memory. The developer should make sure to dereference the object after its work is accomplished. Although the garbage collector endeavors its level best to reclaim memory as much as possible, memory limits can still be exceeded.

Let’s take a look at the following example:

7. Why is synchronization necessary? Explain with the help of a relevant example.

Concurrent execution of different processes is made possible by synchronization. When a particular resource is shared between many threads, situations may arise in which multiple threads require the same shared resource.

Synchronization assists in resolving the issue and the resource is shared by a single thread at a time. Let’s take an example to understand it more clearly. For example, you have a URL and you have to find out the number of requests made to it. Two simultaneous requests can make the count erratic.

No synchronization:

java interview case study

If a thread Thread1 views the count as 10, it will be increased by 1 to 11. Simultaneously, if another thread Thread2 views the count as 10, it will be increased by 1 to 11. Thus, inconsistency in count values takes place because the expected final value is 12 but the actual final value we get will be 11.

Now, the function increase() is made synchronized so that simultaneous accessing cannot take place.

With synchronization:

java interview case study

If a thread Thread1 views the count as 10, it will be increased by 1 to 11, then the thread Thread2 will view the count as 11, it will be increased by 1 to 12. Thus, consistency in count values takes place.

8. In the given code below, what is the significance of ... ?

  • Ability to provide ... is a feature called varargs (variable arguments) which was introduced as part of Java 5.
  • The function having ... in the above example indicates that it can receive multiple arguments of the datatype String.
  • For example, the fooBarMethod can be called in multiple ways and we can still have one method to process the data as shown below:

9. What will be the output of the below java program and define the steps of Execution of the java program with the help of the below code?

The Output we get by executing this program will be

Static Block 1. Value of j = 0 Static method.  Static Block 2. Value of j = 10 Instance Block 1. Value of i = 0 Instance Block 2. Value of i = 5 Instance method.  Welcome to InterviewBit

This is a java tricky interview question frequently asked in java interviews for the experienced. The output will be like this because, when the java program is compiled and gets executed, then there are various steps followed for execution. And the steps are - 

  • Identification of Static Members from top to bottom.
  • Execution of Static variable assignment and a Static block from top to bottom.
  • Execution of the main method.
  • Identification of Instance Members from top to bottom.
  • Execution of Instance variable assignment and Instance block from top to bottom.
  • Execution of Constructor.

In above steps from 4 to 6, will be executed for every object creation. If we create multiple objects then for every object these steps will be performed.

Now from the above code, the execution will happen like this - 

1. In the step of identification of static members. It is found that -

  • static int j.
  • static block.
  • main method.
  • static method_2.

During identification, the JVM will assign the default value in the static int j variable. Then it is currently in the state of reading and indirectly writing. Because the original value is not assigned.

2. In the next step, it will execute the static block and assign the value in static variables.

  • First static block it will print and because execution from top to bottom and original value in j is not assigned. So it will print the default value of 0.
  • After executing static block 1. It will execute the static method_1 because it is called from the static block 1.
  • Then it will assign the original value of 5 in the j variable. And executes the remaining static block.

3. Now it will execute the main method. In which it will create an object for the class InterviewBit. And then the execution of instances will happen.

4. Identify the instance variables and blocks from top to bottom. 

  • Instance block 1.
  • Instance method_1.

Like a static variable, the instance variable also has been initialized with the default value 0 and will be in the state of reading and writing indirectly.

5. It will execute the instance methods and assign the original value to the instance variable.

  • Prints the Instance block 1. And the current value of i is not assigned till now, so it will print 0.
  • Assign the original value to i. Then print instance block 2. And after that instance method will be called and printed because it is being called in the instance block.

6. And at the last step, the constructor will be invoked and the lines will be executed in the constructor.

This is how the java program gets executed.

10. Define System.out.println().

System.out.println() is used to print the message on the console. System - It is a class present in java.lang package . Out is the static variable of type PrintStream class present in the System class. println() is the method present in the PrintStream class.

So if we justify the statement, then we can say that if we want to print anything on the console then we need to call the println() method that was present in PrintStream class. And we can call this using the output object that is present in the System class.

11. Can you explain the Java thread lifecycle?

Java thread life cycle is as follows:

  • New – When the instance of the thread is created and the start() method has not been invoked, the thread is considered to be alive and hence in the NEW state.
  • Runnable – Once the start() method is invoked, before the run() method is called by JVM, the thread is said to be in RUNNABLE (ready to run) state. This state can also be entered from the Waiting or Sleeping state of the thread.
  • Running – When the run() method has been invoked and the thread starts its execution, the thread is said to be in a RUNNING state.
  • A thread is said to be in a Blocked state if it wants to enter synchronized code but it is unable to as another thread is operating in that synchronized block on the same object. The first thread has to wait until the other thread exits the synchronized block.
  • A thread is said to be in a Waiting state if it is waiting for the signal to execute from another thread, i.e it waits for work until the signal is received.
  • Terminated – Once the run() method execution is completed, the thread is said to enter the TERMINATED step and is considered to not be alive.

The following flowchart clearly explains the lifecycle of the thread in Java.

java interview case study

12. What could be the tradeoff between the usage of an unordered array versus the usage of an ordered array?

  • The main advantage of having an ordered array is the reduced search time complexity of O(log n) whereas the time complexity in an unordered array is O(n) .
  • The main drawback of the ordered array is its increased insertion time which is O(n) due to the fact that its element has to reordered to maintain the order of array during every insertion whereas the time complexity in the unordered array is only O(1).
  • Considering the above 2 key points and depending on what kind of scenario a developer requires, the appropriate data structure can be used for implementation.

13. Is it possible to import the same class or package twice in Java and what happens to it during runtime?

It is possible to import a class or package more than once, however, it is redundant because the JVM internally loads the package or class only once.

14. In case a package has sub packages, will it suffice to import only the main package? e.g. Does importing of com.myMainPackage.* also import com.myMainPackage.mySubPackage.*?

This is a big NO. We need to understand that the importing of the sub-packages of a package needs to be done explicitly. Importing the parent package only results in the import of the classes within it and not the contents of its child/sub-packages.

15. Will the finally block be executed if the code System.exit(0) is written at the end of try block?

NO. The control of the program post System.exit(0) is immediately gone and the program gets terminated which is why the finally block never gets executed.

16. What do you understand by marker interfaces in Java?

Marker interfaces, also known as tagging interfaces are those interfaces that have no methods and constants defined in them. They are there for helping the compiler and JVM to get run time-related information regarding the objects.

17. Explain the term “Double Brace Initialisation” in Java?

This is a convenient means of initializing any collections in Java. Consider the below example.

In the above example, we see that the stringSets were initialized by using double braces.

  • The first brace does the task of creating an anonymous inner class that has the capability of accessing the parent class’s behavior. In our example, we are creating the subclass of HashSet so that it can use the add() method of HashSet.
  • The second braces do the task of initializing the instances.

Care should be taken while initializing through this method as the method involves the creation of anonymous inner classes which can cause problems during the garbage collection or serialization processes and may also result in memory leaks.

18. Why is it said that the length() method of String class doesn't return accurate results?

  • The length method returns the number of Unicode units of the String. Let's understand what Unicode units are and what is the confusion below.
  • Code Point: This represents an integer denoting a character in the code space.
  • Code Unit: This is a bit sequence used for encoding the code points. In order to do this, one or more units might be required for representing a code point.
  • The code points from the first plane are encoded using one 16-bit code unit
  • The code points from the remaining planes are encoded using two code units.

Now if a string contained supplementary characters, the length function would count that as 2 units and the result of the length() function would not be as per what is expected.

In other words, if there is 1 supplementary character of 2 units, the length of that SINGLE character is considered to be TWO - Notice the inaccuracy here? As per the java documentation, it is expected, but as per the real logic, it is inaccurate.

19. What is the output of the below code and why?

“bit” would have been the result printed if the letters were used in double-quotes (or the string literals). But the question has the character literals (single quotes) being used which is why concatenation wouldn't occur. The corresponding ASCII values of each character would be added and the result of that sum would be printed. The ASCII values of ‘b’, ‘i’, ‘t’ are:

98 + 105 + 116 = 319

Hence 319 would be printed.

20. What are the possible ways of making object eligible for garbage collection (GC) in Java?

First Approach: Set the object references to null once the object creation purpose is served.

Second Approach: Point the reference variable to another object. Doing this, the object which the reference variable was referencing before becomes eligible for GC.

Third Approach: Island of Isolation Approach: When 2 reference variables pointing to instances of the same class, and these variables refer to only each other and the objects pointed by these 2 variables don't have any other references, then it is said to have formed an “Island of Isolation” and these 2 objects are eligible for GC.

21. In the below Java Program, how many objects are eligible for garbage collection?

In the above program, a total of 7 objects will be eligible for garbage collection. Let’s visually understand what's happening in the code.

java interview case study

In the above figure on line 3, we can see that on each array index we are declaring a new array so the reference will be of that new array on all the 3 indexes. So the old array will be pointed to by none. So these three are eligible for garbage collection. And on line 4, we are creating a new array object on the older reference. So that will point to a new array and older multidimensional objects will become eligible for garbage collection.

22. What is the best way to inject dependency? Also, state the reason.

There is no boundation for using a particular dependency injection. But the recommended approach is - 

Setters are mostly recommended for optional dependencies injection, and constructor arguments are recommended for mandatory ones. This is because constructor injection enables the injection of values into immutable fields and enables reading them more easily.

23. How we can set the spring bean scope. And what supported scopes does it have?

A scope can be set by an annotation such as the @Scope annotation or the "scope" attribute in an XML configuration file. Spring Bean supports the following five scopes:

  • Global-session

24. What are the different categories of Java Design patterns?

Java Design patterns are categorized into the following different types. And those are also further categorized as 

Structural patterns:

Behavioral patterns:

  • Interpreter
  • Template method/ pattern
  • Chain of responsibility
  • Command pattern
  • Iterator pattern
  • Strategy pattern
  • Visitor pattern

J2EE patterns:

  • MVC Pattern
  • Data Access Object pattern
  • Front controller pattern
  • Intercepting filter pattern
  • Transfer object pattern

Creational patterns:

  • Factory method/Template
  • Abstract Factory

25. What is a Memory Leak? Discuss some common causes of it.

The Java Garbage Collector (GC) typically removes unused objects when they are no longer required, but when they are still referenced, the unused objects cannot be removed. So this causes the memory leak problem. Example - Consider a linked list like the structure below -

java interview case study

In the above image, there are unused objects that are not referenced. But then also Garbage collection will not free it. Because it is referencing some existing referenced object. So this can be the situation of memory leak.

Some common causes of Memory leaks are - 

  • When there are Unbounded caches.
  • Excessive page swapping is done by the operating system.
  • Improper written custom data structures.
  • Inserting into a collection object without first deleting it. etc.

26. Assume a thread has a lock on it, calling the sleep() method on that thread will release the lock?

A thread that has a lock won't be released even after it calls sleep(). Despite the thread sleeping for a specified period of time, the lock will not be released.

1. Check if a given string is palindrome using recursion.

/* * Java program to check if a given inputted string is palindrome or not using recursion. */ import java.util.*; public class InterviewBit { public static void main (String args[]) { Scanner s = new Scanner(System.in); String word = s.nextLine(); System.out.println( "Is " +word+ " palindrome? - " +isWordPalindrome(word)); } public static boolean isWordPalindrome (String word) { String reverseWord = getReverseWord(word); //if word equals its reverse, then it is a palindrome if (word.equals(reverseWord)){ return true ; } return false ; } public static String getReverseWord (String word) { if (word == null || word.isEmpty()){ return word; } return word.charAt(word.length()- 1 ) + getReverseWord(word.substring( 0 , word.length() - 1 )); } }

2. Write a Java Program to print Fibonacci Series using Recursion.

In the above code, we are printing the base 2 Fibonacci values 0 and 1. And then based on the length of Fibonacci to be printed, we are using the helper function to print that.

3. Write a Java program to check if the two strings are anagrams.

The main idea is to validate the length of strings and then if found equal, convert the string to char array and then sort the arrays and check if both are equal.

4. Write a Java Program to find the factorial of a given number.

public class FindFactorial { public static void main (String[] args) { int num = 10 ; long factorialResult = 1l ; for ( int i = 1 ; i <= num; ++i) { factorialResult *= i; } System.out.println( "Factorial: " +factorialResult); } }

5. Given an array of non-duplicating numbers from 1 to n where one number is missing, write an efficient java program to find that missing number.

Idea is to find the sum of n natural numbers using the formula and then finding the sum of numbers in the given array. Subtracting these two sums results in the number that is the actual missing number. This results in O(n) time complexity and O(1) space complexity.

6. 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
  • Step 2: 10 => 1+0 = 1 => Hence 163 is a magic number

7. Write a Java program to create and throw custom exceptions.

We have created the exception class named with CustomException and called the base exception constructor with the error message that we want to print. And to avoid handling exceptions in the main method, we have used the throws keyword in the method declaration.

8. Write a Java program to reverse a string.

In the above code, we are storing the last character from the string to the first and the first value to the last in the output character array. And doing the same thing in the loop for the remaining 2nd to n-1 characters. This is how the string will be reversed.

9. Write a Java program to rotate arrays 90 degree clockwise by taking matrices from user input.

In the above code, for rotating the matrix to  90 degrees we are first transposing the matrix so the row becomes the column. And after that, we are reversing each row in the matrix. So this is how the matrix got rotated.

10. Write a java program to check if any number given as input is the sum of 2 prime numbers.

18 = 13 + 5 18 = 11 + 7

In the above code, for any number n , we find all the 2 pairs of numbers that are added together resulting in n . And each checking number if it is prime. If it is prime then we are printing that.

11. Write a Java program for solving the Tower of Hanoi Problem.

In the above code we are first moving the n-1 disk from Tower A to Tower B , then moving that nth disk from Tower A to Tower C , and finally, the remaining n-1 disk from Tower B to Tower C . And we are doing this recursively for the n-1 disk.

12. Implement Binary Search in Java using recursion.

In the above code, we are finding the middle element each time and checking if the element is in the middle or not. If it is not, then we check on which side from the middle it exists. And Recursively searching on the particular subarray. So this way we are reducing the search space by 2 every time. So the search time is very low.

1. Conclusion

Java is one of the simple high-level languages that provides powerful tools and impressive standards required for application development. It was also one of the first languages to provide amazing threading support for tackling concurrency-based problems. The easy-to-use syntax and the built-in features of Java combined with the stability it provides to applications are the main reasons for this language has ever-growing usage in the software community.

Interview Preparation Resources

  • How to Become a Java Developer?
  • How much does a Java Developer earn in India?
  • Java Projects
  • Java Programming Questions for Interview
  • Java 8 Interview Questions
  • Java String Interview Questions
  • Spring Interview Questions
  • Hibernate Interview Questions
  • Java Collections Interview Questions
  • Array Interview Questions
  • Design Patterns Interview Questions
  • Multithreading Interview Questions
  • Java Tutorial
  • Advance Java MCQ
  • Difference Between C++ and Java
  • Difference Between C and Java
  • Difference Between Java and Javascript
  • Hashmap vs Hashtable in Java
  • Kotlin Vs Java
  • Java Vs Python
  • Features of Java 9
  • Java 8 Features
  • Java Frameworks
  • Java Developer Skills
  • Java 11 Features
  • Additional Technical Interview Questions
  • JAVA SE Download

Coding Problems

What is the component used for compiling, debugging, and executing java programs?

What component does the task of bytecode to machine code conversion?

Which of the following is the functionality of the java interpreter?

When an object has its own lifecycle and its child object cant belong to another parent object, what is it called?

What is the output of the below piece of code?

What is the output of the following code?

Which of the following happens when the garbage collection process kicks off during the execution of the thread?

What is the output of the below code?

What is the functionality of Class.getInstance() ?

  • 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 Javascript Compiler
  • Online Python Compiler
  • Interview Preparation
  • 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 +

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

Core Java Interview Questions

We've developed a list of Advanced Core Java Interview Questions to assist you ace your interview and land your ideal job as a Core Java Developer.

  • Abstraction in Java
  • Clojure Tutorial
  • Control Statements in Java
  • Data Types in java
  • Top 9 Java EE Frameworks
  • Java EE vs Spring Framework
  • Java Frameworks List - Top 14 Java Frameworks
  • Java Interview Questions
  • Java Tutorial
  • Java Web Dynpro Interview Questions
  • JavaFX Interview Questions
  • Method Overloading in Java
  • Multithreading in Java
  • List of Popular Open Source Java Build tools
  • Operators in Java
  • Program Logics in Java
  • String Handling in Java
  • Why You Should Learn Java Programming
  • Data Structures Interview Questions
  • Exception Handling in Java
  • Multithreading Interview Questions
  • Design Patterns Interview Questions and Answers
  • C++ Interview Questions and Answers
  • JSP Interview Questions
  • EJB Interview Questions
  • SOAP in Web Services
  • JPA Interview Questions
  • DXC Interview Questions and Answers
  • Java Architect Interview Questions
  • Java Concurrency Interview Questions
  • What is Java Concurrency?
  • What is JPA - Complete Tutorial Guide
  • What is EJB?
  • Java Collections Interview Questions
  • Java Swing Tutorial
  • Java Stream Tutorial
  • Linked List Interview Questions
  • Compiler Design Interview Questions
  • Java Collection Tutorial
  • Java Stream Interview Questions
  • Thymeleaf vs JSP
  • Thymeleaf Tutorial - What is Thymeleaf
  • Socket Programming in Java - What is TCP
  • Apache Tomcat Interview Questions
  • Capgemini Interview Questions
  • Zoho Interview Questions
  • PwC Interview Questions
  • Hexaware Interview Questions
  • Intuit Interview Questions
  • Tech Mahindra Interview Questions
  • Qualcomm Interview Questions
  • Arcesium Interview Questions
  • PayTM Interview Questions
  • DXC Technology Interview Questions
  • Java Developer Job Description
  • MAQ Software Interview Questions
  • Amdocs Interview Questions
  • TCS NQT Interview Questions
  • Virtusa Interview Questions
  • Siemens Interview Questions
  • Tricky Java Interview Questions
  • Explore real-time issues getting addressed by experts
  • Test and Explore your knowledge
  • Experienced

If you're looking for Core Java Interview Questions & Answers for Experienced or Freshers, you are at the right place. There are a lot of opportunities from many reputed companies in the world. According to research Core Java has a market share of about 10.1%.

So, You still have the opportunity to move ahead in your career in Core Java Development. Mindmajix offers Advanced Core Java Interview Questions 2024 that help you in cracking your interview & acquire a dream career as Core Java Developer.

We have categorized Core Java Interview Questions into 2 levels they are:

Frequently Asked Core Java Interview Questions

  • What are the principle concepts of OOPS?
  • What is Encapsulation?
  • What is the difference between Abstraction and Encapsulation?
  • What is Polymorphism?
  • Explain the different forms of Polymorphism.
  • What is Dynamic Binding?
  • What is method overriding?
  • What is the difference between method overloading and method overriding?
  • Is it possible to override the main method?
  • How do you prevent a method from being overridden?

Core Java Interview Questions For Freshers

1. what are the principle concepts of oops.

There are four principle concepts upon which object-oriented design and programming rest. They are:

  • Abstraction
  • Polymorphism
  • Inheritance
  • Encapsulation.

(i.e. easily remembered as A-PIE).

2. What is Abstraction?

Abstraction refers to the act of representing essential features without including the background details or explanations.

3. What is Encapsulation?

Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object.

[ Learn Complete Java Tutorial ]

4. What is the difference between Abstraction and Encapsulation?

Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing its inside view, where the behavior of the abstraction is implemented.

  • Abstraction solves the problem on the design side while Encapsulation is the Implementation.
  • Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer's needs.

Top 10 Programming Languages that you need to watch out to boost your career in 2023

5. What is Inheritance?

Inheritance is the process by which objects of one class acquire the properties of objects of another class. A class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Inheritance is done by using the keyword extends.

The two most common reasons to use inheritance are:

  • To promote code reuse
  • To use polymorphism.

[ Check out Data Types in Java ]

6. What is Polymorphism?

Polymorphism is briefly described as “one interface, many implementations.” Polymorphism usage to something in different contexts – specifically, to allow an entity such as a variable, a function, or an object to have more than one form.

7. How does Java implement polymorphism?

Inheritance, Overloading, and Overriding are used to achieve Polymorphism in Java. Polymorphism manifests itself in Java in the form of multiple methods having the same name.

In some cases, multiple methods have the same name, but different formal argument lists (overloaded methods). In other cases, multiple methods have the same name, same return type, and the same formal argument list (overridden methods).

8. Explain the different forms of Polymorphism.

There are two types of polymorphism, one is Compile time polymorphism and the other is run time polymorphism. Compile-time polymorphism is method overloading. Runtime time polymorphism is done using inheritance and interface.

Note : From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:

  • Method overloading
  • Method overriding through inheritance
  • Method overriding through the Java interface.

[ Check out Top Java EE Frameworks ]

9. What is runtime polymorphism or dynamic method dispatch?

In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.

10. What is Dynamic Binding?

Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance.

11. What is method overloading?

Method Overloading means having two or more methods with the same name in the same class with different arguments. The benefit of method overloading is that it allows you to implement methods that support the same semantic operation but differ by argument number or type.

Important Note:

  • Overloaded methods MUST change the argument list.
  • Overloaded methods CAN change the return type.
  • Overloaded methods CAN change the access modifier.
  • Overloaded methods CAN declare new or broader checked exceptions.
  • A method can be overloaded in the same class or in a subclass.

12. What is method overriding?

Method overriding occurs when a subclass declares a method that has the same type of arguments as a method declared by one of its superclasses. The key benefit of overriding is the ability to define behavior that’s specific to a particular subclass type.

Note : The overriding method cannot have a more restrictive access modifier than the method being overridden (Ex: You can’t override a method marked public and make it protected). You cannot override a method marked final. You cannot override a method marked Static.

[ A Complete Guide to Control Statements in Java ]

Core Java Interview Questions for Experienced

13. what is the difference between method overloading and method overriding.

Overloaded Method:

  • Arguments – Must Change
  • Return type: Can Change
  • Exceptions – Can Change
  • Access – Can Change
  • Invocation – Reference type determines which overloaded version is selected. Happens at compile time.

Overridden Method:

  • Arguments – Must not Change
  • Return type: Can’t change except for covariant returns
  • Exceptions – Can reduce or eliminate. Must not throw new or broader checked exceptions
  • Access – Must not make more restrictive (can be less restrictive)
  • Invocation – Object type determines which method is selected. Happens at runtime.

14. Can overloaded methods be overridden too?

Yes, derived classes still can override the overloaded methods. Polymorphism can still happen. The compiler will not be binding the method calls since it is overloaded, because it might be overridden now or in the future.

15. Is it possible to override the main method?

No, because the main is a Static method. A Static method can’t be overridden in Java.

16. How to invoke a superclass version of an Overridden method?

To invoke a superclass method that has been overridden in a subclass, you must either call the method directly through a superclass instance or use the super prefix in the subclass itself. From the point of view of the subclass, the super prefix provides an explicit reference to the superclass’s implementation of the method.

17. What is Super?

Super is a keyword that is used to access the method or member variables from the superclass. If a method hides one of the member variables in its superclass, the method can refer to the hidden variable through the use of the super keyword. In the same way, if a method overrides one of the methods in its superclass, the method can invoke the overridden method through the use of the super keyword.

Note: You can only go back to one level. In the constructor, if you use super(), it must be the very first code, and you cannot access any of these. xxx variables or methods to compute its parameters.

18. How do you prevent a method from being overridden?

To prevent a specific method from being overridden in a subclass, use the final modifier on the method declaration, which means “this is the final implementation of this method”, the end of its inheritance hierarchy.

19. What is an Interface?

An interface is a description of a set of methods that conform to implementing classes must-haves.

  • You can’t mark an interface as final.
  • Interface variables must be Static.
  • An Interface cannot extend anything but another interface.

Stay updated with our newsletter, packed with Tutorials, Interview Questions, How-to's, Tips & Tricks, Latest Trends & Updates, and more ➤ Straight to your inbox!

Remy Sharp

Ravindra Savaram is a Technical Lead at Mindmajix.com . His passion lies in writing articles on the most popular IT platforms including Machine learning, DevOps, Data Science, Artificial Intelligence, RPA, Deep Learning, and so on. You can stay up to date on all these technologies by following him on LinkedIn and Twitter .

scrollimage

Copyright © 2013 - 2024 MindMajix Technologies

Java Gently, Third Edition by Judith Bishop

Get full access to Java Gently, Third Edition and 60K+ other titles, with a free 10-day trial of O'Reilly.

There are also live events, courses curated by job role, and more.

List of Examples and Case Studies

Get Java Gently, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Don’t leave empty-handed

Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.

It’s yours, free.

Cover of Software Architecture Patterns

Check it out now on O’Reilly

Dive in for free with a 10-day trial of the O’Reilly learning platform—then explore all the other resources our members count on to build skills and solve problems every day.

java interview case study

AI-Driven Custom Software Development

case interviews

Here’s Why We Do Case Interviews for Software Engineers

Years ago, we uncovered one of the most problematic elements of the Software Engineer hiring process: they’re not very realistic.

At Revelry, we use case interviews to create the best representation of what it’s like to perform successful work as a Software Engineer. Here’s why we think the other methods aren’t useful, and how we interview to add the best Revelers to the team.

Problem: Useless whiteboarding exercises

A company once came to us to hire a technical team in the interim, since they were having a hard time hiring new Software Engineers.

They put me through their technical interview – the one they had been giving to their prospective new employees.

I was asked to implement a red-black tree as a class in JavaScript, and then demonstrate how to balance the tree structure. Look, this is college Computer Science “Data Structures and Algorithms” class material. And I’m extremely rusty on it.

I pushed back, asking the interviewer just how often they were balancing red-black trees in their JavaScript code. The answer, of course, was never. So I asked for a real problem to solve, and this customer became a loyal client for years.

This is why we do case interviews, not whiteboard challenges. Whiteboard challenges test for things we don’t use day-to-day in our work, and they  don’t  test for all the skills we  do  use.

Also problematic: Other “hands-on coding exercises”

There are a few other common types of “hands-on coding exercises”. Here’s why we don’t think they’re helpful, either.

Problematic screening exercise: The online or take-home code test

For this test, you give the interviewee a set of programming problems that the candidate does on their own. Then they hand it in, like a college exam.

This type of test can’t show a candidate’s capacity for communication, their ability to ask good questions, or their ability to bridge between developer and non-developer worlds.

To give this test, you have to phrase the questions such that they know exactly what to do, since that’s the last communication they’ll receive from you before answering. That doesn’t leave any space for the discovery process.

Do you want to spend the next few years feeding your team exact test-like instructions?

Still problematic, but better: Working in your real codebase

Inviting your candidate to work in your real codebase is better in some ways. At least they have more access to the interviewers in this scenario.

But there are still problems. For one, you are requiring someone to answer you in an exact technical stack with which they might not be familiar. This isn’t necessarily representative of their skills, since good developers can learn a new stack very quickly.

I’d rather hire someone who is an excellent general problem solver and communicator, and a polyglot programmer, than someone who knows my exact stack but lacks those other qualities.

We like case interviews because they’re realistic

Case interviews are a format of interview that create a realistic scenario, allowing the candidate to apply the real skills they would need to be successful in our work.

A case interview tests not just programming skills, but communication, estimation, and risk management. Perhaps most importantly, it tests for the ability to translate a problem statement into a working technical solution. Problem statements and intended outcomes are normally articulated by a non-technical person, so this translation skill is so crucial in our work.

We interview for the job we have: helping people to solve their organizations’ problems, not giving computer science lectures.

Here’s what a case interview looks like

At Revelry, the case interview starts with a scenario. We have a few case scenarios which are based on actual past projects (with names changed to protect both the innocent and the guilty).

The interviewee is allowed to ask as many questions as they like, at any point.

And they should. In our work, we need to ask clarifying questions to make sure we’re solving the right problem and that the solution we’re proposing will really work.

We ask questions in return, starting with broad questions.

  • What does this client need?
  • What do you think the hardest part of this project would be?
  • How would you figure out what technology to use to solve this?

Next, we ask more specific questions.

  • What tables would we need in our database?
  • What kind of columns might each of those tables have?
  • How do they relate to each other?

Then, we program.

The interviewee shares their screen. We ask them to implement one specific feature of the solution. They can use any programming language and framework they want. We don’t ask them to compile or run the code, because setting up a new project with boilerplate and scaffolding takes too long. And because we trust that people can use a generator or read the documentation when they need to.

Since we don’t ask them to work in a real project directory, we also don’t focus on getting method signatures right from memory or even having perfect syntax. We focus on whether they have a solid grasp on the concepts of practical web development and whether they can faithfully translate a non-technical problem statement and turn it into a working technical solution.

This is one of the ways we’ve built one of the best teams in Software Engineering. We treat interviewees like they are already on the team, and then we see how they do.

We're building an AI-powered Product Operations Cloud, leveraging AI in almost every aspect of the software delivery lifecycle. Want to test drive it with us? Join the ProdOps party at ProdOps.ai .

Related Posts

  • Apprenticeship (9)
  • Artificial Intelligence (21)
  • Back-End Engineering (115)
  • Blockchain (10)
  • Elixir / Phoenix (21)
  • Front-End, UI / UX Engineering (34)
  • Insights (44)
  • Javascript (20)
  • Leadership (20)
  • Meet The Team (19)
  • Off the Beaten Path (4)
  • Peerbot (1)
  • Process (17)
  • ProdOps (1)
  • Product Management (27)
  • React / React Native (5)
  • Remote Work (17)
  • Revelry News (12)
  • RevTWIL (13)
  • Ruby on Rails (4)
  • Startup Studio (3)
  • Technical Consulting (21)
  • Testing and Security (5)
  • Wordpress (2)
  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot
  • Top 50 Java Project Ideas For Beginners & Advanced
  • Currency Converter
  • Brick Breaker Game
  • Attendance Management System
  • Number Guessing Game
  • Tic-Tac-Toe Game
  • Simple Banking Application
  • Library Management System
  • Word Counter
  • ATM Simulation System
  • Airline Reservation System
  • Smart City Project (City Guide Project)
  • A Text-Based Adventure Game
  • Grading System in Java
  • School Management System
  • Pharmacy Management System
  • Supermarket Billing System
  • Online Quiz Management System
  • HelpDesk Management System
  • Notes and Password Manager
  • Supply Chain Management System
  • Virtual Private Network (VPN) for an Office
  • Flappy Bird Game
  • Scientific Calculator in Java

Top 50 Java Project Ideas For Beginners & Advanced

Java is one of the most popular and widely used programming language and a platform that was developed by James Gosling in the year 1982. It is based on the concept of Object-oriented Programming. A platform is an environment in that develops and runs programs written in any programming language. Java is a high-level, object-oriented, secure, robust, platform-independent, multithreaded, and portable programming language.

Creating Java projects helps sharpen your skills and boosts your confidence as a developer. It provides practical application of theoretical knowledge. Building a portfolio showcasing completed projects empowers you for job interviews, giving you solutions, code, apps, and projects to display to recruiters.

Java Project Ideas For Beginners

With such amazing facts about Java, you would surely want to build some amazing applications using it, be it in any field like big data, mobile, enterprise, financial, or commerce. This article majorly focuses on projects which can be used by college students. Whether you’re from the first year, second year, third year, or fourth year. 

In this article, you’ll learn about some amazing Java projects starting from beginner level, intermediate to advanced level. These projects can be utilized for college assignments and will assist you in developing your Java skill set.

Table of Contents Beginner Level Java Projects Intermediate Level Java Projects Advanced Level Java Projects

Beginner Level Java Projects Ideas

The below-given list consists of some beginner-level Java project ideas which can be used as major projects by the students or professionals.

1. Currency Converter 

This project is a very basic project in Java that is used to convert a currency from one to another. A web-based interface for converting currency and getting the output value, for example, here displays converting the currency of the US dollar to INR. 

Abstract: We see variations with different countries using different currencies. Be aware of the current exchange prices in the market and then can convert from one currency to another. A calculator-like application, developed using Ajax, Applet, and web features of Java servlets. You also get a regular update when there’s a change in the value of the country’s currency and also the conversion rate. 

People use this application basically for business, shares, and finance-related areas where currency exchange and money transfer happen daily. You get a preferred choice to convert any country’s currency. Just enter the amount, the currency to which you want to transform to, click enter and you get the output.

Technologies Required: Java programming language, Java Servlets Web Features, Applet, and Ajax.

2. Brick Breaker Game

One of the pleasant ways to study technology is through implementing game applications. It may not be easy but developing this Java project will make you learn a lot of new things. This game development project will provide you with java experience and essential animation techniques with their integration. 

Abstract: Many of you already heard of the brick breaker game. It has a small ball that knocks the bricks taking the help of a small platform at the base. The player handles this platform and tries to bounce the ball through that platform. In this project, the scoring depends on the number of bricked-broken, i.e., the more you destroy the bricks, the more you score. 

If you missed the chance for the ball to bounce, then the game is over. This project is basically for beginners who are looking for a minor project. This simple project will surely help you with your first-year project or also as an implementation for fun purposes. 

Technologies Required: Java, Game development, JFrame, JPanel, and Java Graphics Kit.

3. Attendance Management System

An attendance management system is one of the major projects for university-level graduates. The project can be built using Java, the MVC architecture could be followed, and Maven as a built tool. It uses MySQL as a backend for database management and uses a tomcat server to deploy the application in order to see it working live. 

Abstract: This project is a web application that manages the attendance of any student in school or college, also employees in an organization. It has an admin feature that holds the access to do any kind of changes like update, delete, and add user records to the list. 

Various users of the application where users can access are:

Technologies Required: Java Servlet , MVC architecture, Maven MySQL , Tomcat Server JSP, HTML , CSS , and JavaScript .

4. Number Guessing Game

This number guessing game is an easy project built on Java where the player has to guess a number given in between a range. If the guessed number is right, the player wins else, loses. It also has the concept of limited attempts where the player has to guess the number within the limited attempts given. 

Abstract: The UI has an input value option where the player has to enter the guessed value, it also displays the time remaining to guess. After completing the limits given, if the guessed number is right, the player wins else loses. The range between the number can be from 1 to 100 or 1 to 1000. Also, if the number you’ve guessed is high or low to the actual value, the application sends you an alert “Too High” or “Too Low”. After the limited attempt is completed, the actual value is revealed. 

Technologies Required: Java Programming Language and Random Class in Java .

5. Tic-Tac-Toe Game

The Tic-Tac-Toe game application is a simple project developed using GUI (Graphical User Interface) in Java. It is very easy to understand and play, players generally prefer this kind of game when they’re bored and want something to play which is quick and easy.

Abstract: The game starts with two players as active members, having a one-print board on the screen which displays 9 boxes (i.e., 3×3). The first person who starts the game has to enter either X or O for any one box, followed by the other player entering the other X or O (opposite to what the first player has entered). this continues unless any one of them gets a line cut either diagonally or straight. And the person who founds the line is the winner of the game. 

Technologies Required: Java, Java Swing, Java GUI (Graphical User Interface), and JFrame.

6. Simple Banking Application

Simple Banking Application is a simple Java project for beginners to start their career in coding. You’ll learn about Scanner class to take inputs, and the basics of strings, loops, methods, and conditional statements. Here, simple banking operations like deposit, withdrawal, checking balance, exit, etc. 

Abstract: In this modernized world, where time is money, everyone has got the habit of doing their tasks online. Within a click, a task is done. You get this application to make transactions just by sitting in your comfort zone. Every operation like money transfer and balance inquiry can be done in seconds. 

Technologies Required: Java Programming Language, Oracle Database (if needed), and Java methods.

7. Library Management System 

Learning Management System, this project build on Java is a great way to update the record, monitor and add books, search for the required ones, taking care of the issue date and return date. It comes with basic features like creating a new record and updating and deleting it. 

Abstract: We rely on web-based applications for every task, be it small or big. This contains two sections – the admin and users section. The admin handles the record of the users and the user handles the entry of books being issued to him/her. Also, there can be modules that display the data of books available in the library, a search button to search for the required book, and the final payment method for the charges of the book or fine imposed. 

Technologies Required: Java, Java Swing Library, MySQL JDBC Connector, MySQL Community Server, and rs2xml.jar (used to display the data in a table format).

8. Word Counter 

A simple project for beginners is good to start. It can be built using Swing in Java. Here, the application tells you the no of words, the entered paragraph has. 

Abstract: This Java application is best suited for counting words. Remember, our childhood days when we were asked to write an essay on a given topic where the word length should be 500 or 1000. This application comes with a feature that could help you. Along with word count, it also tells you the number of characters, words, and paragraphs it has. Also, it is completely free to use and there’s no word count limit. 

Technologies Required: Java, Java Swing, Java Framework (JFrame), and Applet. 

9. ATM Simulation System

ATM simulation system is a simple Java project for beginners. It is a kind of personal banking system where users can perform various transactions like withdrawals, deposits, and checking the balance of the account in just one click. It has a Graphical User Interface (GUI) to make the process user-friendly. 

Abstract: The introduction of the application came up with two features which have an admin mode and the user mode. The admin mode is responsible for controlling the entire system like adding and deleting accounts and updating the records of the user. The user-mode takes care of the deposit, withdrawal, and checking of the account balance. The whole process of this system is automated, from PIN (Personal Identification Number) validation to the transaction. The card details will be secured enough by encrypting the details in the database and will only be accessible to the authorized user. The UI of the application contains a profile of the user, accounts added to it, and an option to withdraw, deposit and update details of the account. 

Technologies Required: Java, J2EE, Apache Tomcat Web Server, and Oracle.

10. Airline Reservation System

This Java project is built to help the customers book tickets online, check the availability of seats, get the details of the flight arrival, select the class they want to choose, and departures reserve seats for national or international flights. 

Abstract: This web-based Java project helps you in searching from pick-up location to destination, and filters out the flight details with timing, and available seats. It consolidates data from all airlines using globally distributed systems. After entering all the required details of the customer, it asks you to choose a flight with a preferred time slot, complete the payment, and book the ticket. It provides rates in real-time to customers as well as to travel agents. It also has two sections where you get to book a national and an international flight wherein you can book a domestic or international flight as per your choice. 

Technologies Required: Core Java, HTML, JavaScript, and SQL Database.

11. Smart City Project (City Guide Project)

Smart City is a web-based application built using Java. It stores details of a city and displays information about the city such as hotels, shopping marts, restaurants, tourist places, transportation modes, and also some general info. This acts as a guide to the new visitors.

Abstract: Tourists and even general people travel from one place to another in order to explore or for employment purposes but before they explore, they want to get an insight data about the place. So, to help them with this, a simple city project can be the best guide for them. It is a web-based application written in Java which basically guides you about the place you’re going to visit. You can access all the details of the city. In this application, users need to sign up by entering input details and then can access all the required details of the city. It contains various modules like admin, tourism, business, and student wherein users can switch to the module as per the requirement.  

Technologies Required: Java, JDBC ODBC 2.0 drivers, Oracle Database, J2EE, AJAX, and XML.

12. A Text-Based Adventure Game

A Text-Based Adventure game, built using Java and Data Structures is an interesting game where the player follows the commands given to him. This web-based gaming app is often referred to as interactive fiction.  

Abstract: This game has a central character called the “Adventurer” which is like an object who represents the player. With the help of the object, tracking of the actual player can be made easy, also can find where the player is. The role of the adventurer is to type the commands which consist of one or two words. The commands which have to be followed can be Go, Look, Take, Drop, Use, and Exit. It contains the following classes TextAdventure, AdventureModel, Adventurer, and a number of rooms. 

Technologies Required: Java programming language, Java objects and classes, and Array and Hashmaps.

13. Grading System in Java

This project built using Java is an important one to grade students based on their markings. It is the best project to start for beginners and has a GUI (Graphical User Interface) design. 

Abstract: The main aim to build this project is to help schools and universities to manage the details of the students (like name, class, total subjects, marks achieved, etc) and rank them on the basis of marks. It manages the calculation of the average marks achieved and ranks the student on the basis of marks. It stores the data of students in a MySQL database. The project is built on Java and has a fully GUI (Graphical User Interface). It has all the features like managing the records of students, integrating all records of examinations, displaying all the information, and keeping a track of it. 

Technologies Required: Java, Java Swing, MySQL Database, and JPanel.

14. School Management System 

The School Management System is a Java application that stores records of schools be it related to students, teachers, and staff. 

Abstract: This application’s objective is to help the school management system in managing the data easily. The manual system could be a complicated one when it comes to keeping the records so, there comes the role of this project. It holds personal records of students, teachers, and staff. This system contains modules for different roles be it admin, student, staff, and teacher. Here, the admin has to be responsible for maintaining the records in the database like adding users, updating the details of the user, and deleting the user’s profile. 

Technologies Required: Java, MS Access database, Java Swing, Java Graphical User Interface (GUI), and JFrame.

15. Pharmacy Management System

Pharmacy Management System is a web-based application built using Java that offers you the facility to order medicines, consult doctors and keep track of all your orders online by just signing up with a registered mail id. 

Abstract: This application is of great help to the users who regularly goes for body check-up because this application gives you the comfort of consulting with a doctor at your comfort place. It comes with an excellent and friendly user interface comes with an automated billing system. It has an integrated chat feature where you can consult with a doctor regarding your health and it also tells you details of medicines and you can also track the status of ordered items. 

Technologies Required: Java, Java Swing, AWT, JDBC, and MySQL Database.

16. Supermarket Billing System

This web-based application is a Java project that is usually built for keeping the sales recording made on a daily basis. It uses a MySQL database for recording the data of the users, products, and orders made by the user (customer). 

Abstract: The web-based Java application is implemented to keep a record of the products, status of the products orders, and user’s history. This UI is made in terms that it displays records of bills made on that particular day, items added to the new bill also have an automated system that calculates the bill with GST and other applied taxes and has a print button to print the copy statement of the bill. It has an admin module that is responsible for adding, updating, or deleting records of the bill. It maintains a database to store the items list, categories, and buyers list.

Technologies Required: Java, JDBC, MySQL Database, JSP, JavaScript, servlet, HTML and Ajax.

17. Online Quiz Management System

You must have definitely used this application during your school days when you were asked to attend an MCQ-based test. This Online Quiz Management System can be built using Java which contains different sections for questions, marks, and subjects.

Abstract: This Java-based project is online software that is a kind of an online platform for conducting mock tests and competitions. The UI is built in such a way that it displays the login button where the user has to sign in to begin the test, followed by entering the details of the test (which could be a unique key), then it displays the no of questions, time duration, and a “START” button to start the test. After completing the test, it asks you to review the answers and then submit it using the “SUBMIT” button. The admin module gives you access to the user’s profile. 

Technologies Required: Java, J2EE, MySQL Database, and JDBC.

18. HelpDesk Management System

HelpDesk Management System built using Java, Servlet, and MySQL is a project made with the intention to help individuals raise a complaint regarding a ticket issued to them. It uses the MVC architecture design and Servlet can manage the request and response made. 

Abstract: You face an issue, you raise a complaint, and a ticket ID is generated which can be used as a reference to resolve the issue. This application can be used in society, schools, organizations, and even in public places where people facing any kind of issues can register a complaint using the application. As soon you raise a complaint, a notification goes to the admin who verifies it and then reverts back to you after rectifying the issue. It includes features like Track, Issue, Ticket ID, Help Desk, Network, and Issues. It contains an admin and user module.

Technologies Required: Java, J2EE, HTML, JavaScript, MySQL database, Tomcat Server, JDBC, and Servlet.

19. Notes and Password Manager

This application is similar to a To-Do List app which helps you to complete your daily tasks and keep track of ongoing tasks. It also has a password for the users to log in to keep the data secure. 

Abstract: This application is of great help when individuals have a lot of tasks to perform where some of them have to be done on priority. This application keeps a track of your daily tasks and helps you in completing them. This can be used by individuals and even by organizations to manage daily tasks. This saves their time as it stores their data in a centralized database for each user. The steps to follow are setting up the details, authenticating it with an authorized user, and managing notes and passwords. It comes with basic functionalities such as a login page, home page, note page, and updating details on the note page. 

Technologies Required: Java, Android, XML, and Firebase.

20. Supply Chain Management System

Supply Chain Management System is a Java project for beginners where different operations such as inventory, storing, handling, and moving raw and finished goods to the final destination are completed. 

Abstract: This project helps enterprises to move materials from source to destination. It is generally used by the production sector where sellers can add and update the details of the goods and the buyers can contact them regarding the booking of orders. Buyers can also check the availability of the goods and keep track of the status. It uses MS Access as a back-end, Apache Tomcat as a server, and HTML and CSS to design its front-end with Java. The main objective of this application is to avoid the communication gap between dealers and clients. There’s also a feedback feature for the goods received. 

Technologies Required: Java, JDBC, JSP, HTML, and MS-Access Database

Intermediate Level Java Projects Ideas

The below-given list consists of some intermediate-level Java project ideas which can be used as major projects by the students or professionals.

21. Virtual Private Network (VPN) for an Office

Virtual Private Network (VPN) developed using Java can be your minor or major project. It works the same as WAN (Wide Area Network), and provides a private network across the public, for example, the Internet. A point-to-point virtual connection through traffic encryption, virtual tunneling protocols, or dedicated connections. 

Abstract: This application built using Java provides a secure and private connection to the organizations. It can be used on office premises, as private networks and it can also be the best means to share information. This project also has three modules which are admin and marketing where the admin’s role is to handle the data stored of the members and the training module checks for the testing and networking part, and the marketing. 

Technologies Required: Java, Java Servlet, J2EE, Apache Tomcat Server, HTML, and JavaScript.

22. Flappy Bird Game

Flappy bird game is a very simple Java-based gaming app in which the main character (which is the bird) has to reach the final destination after crossing all the hurdles. The use of the swing component in Java is perfect in this case.

Abstract: In this gaming application, the player has to control the movement of the bird. The fabby bird only ascends when there’s a tap by the player and descends the rest of the time. The count increase by 1 when the fabby bird passes one hurdle, also the time duration is counted. There shouldn’t be a collision with any hurdle, or else the game ends. 

Technologies Required: Java, Java Swing, Java AWT, and OOPS.

23. Scientific Calculator in Java

A Scientific calculator built using Java is a general-purpose application whose primary objective is to perform basic mathematical operations and also perform some essential and tricky solutions to trigonometric functions, logarithms, etc. 

Abstract: Here, Java Swing can be used to implement this project. It performs mathematical operations like addition, subtraction, multiplication, division, trigonometric operations, finding log values, etc. You get buttons to enter the input value and give the output within a second. In the program’s code, the use of switch cases can be seen to perform operations as per the case. The Scanner class can be used to take input from java.util package. 

24. Simple Search Engine

You search for anything using a search engine so building a simple search engine can be one of the best projects. Applying a ranking algorithm can give better results.

Abstract: Simple Search Engine is a Java application developed using Servlets, SQL Server, and Oracle database.  It can include features like a search bar, which displays the top 30 websites related to the keyword searched. The database containing resource description is described in SOIF (Summary Object Interchange Format) format. The interaction with the search server to access the database is dependent on the Java interface provided by classes in Java SDK. Your search engine contains a history of the pages you searched for, pages visited in the past few days, accounts linked with it, etc. 

Technologies Required: Java, Java Servlet, Oracle or SQL Database, JDBC, Apache Tomcat, and JSP.

25. Online Voting System

An online Voting System built using JSP and Servlet can be the best project for college students. This project is designed to automate the voting process where multiple parties are added and then with the maximum votes, a leader is chosen. 

Abstract: The main objective to build this web-based application is to reduce the time at the voting booth. The UI has different sections which display a login page to enter the portal, different parties with their symbol, an option to choose among them, and then to submit the entry. It uses HTML, CSS, and bootstrap in the front-end, MySQL is the database used, and also it uses an MVC design pattern. The user has to vote for the preferred party anonymously, but the voter’s information and total votes will be stored in the database. 

Technologies Required: Java, JSP, HTML, CSS, MySQL, and Tomcat Apache Server.

26. Online Book Store 

Online Book Store is an application that displays lists of books available in the store where you can purchase or even return them. You can check for the value of the book and buy it by sitting in your comfort place. 

Abstract: The application created using Java allows users to purchase a book by checking for the availability of the book. The user has to sign up, check for the book, enter the credit card details, complete the payment and order the book. There are two modules in this application – the admin and the user. The admin is responsible for the entry of details and the user makes orders. Also, you can see the categories of the book such as Software, History, English, Science, etc. All the CRUD operations are performed by the admin.

Technologies Required: Java, HTML, CSS, JavaScript, Java Servlet, MySQL, and Tomcat server.  

27. CGPA Calculator in Java

This CGPA Calculator built using Java is a web-based application that is of great help to university students. It can be built as a major project during your college days. 

Abstract: This project can be built on eclipse using Maven and uses MVC architecture. It uses MySQL to store the data. This application creates a mark sheet for students and then calculates the CGPA. Here, also the admin is held responsible for entering the details, managing the user details, etc. In the UI, you can view a search key to enter the enrollment number and you get the details displayed in seconds. All the marks for the subjects are given semester-wise. When marks of all the subjects are entered, calculated CGPA will be auto-generated. 

Technologies Required: Java, HTML, CSS, JavaScript, JSP, Java Servlet, MVC, Maven, MySQL, and Tomcat server.

28. Snake Game in Java

Remember, those days when you used to play the snake game on Nokia mobile phones. This snake game can be implemented fully using Java and uses a database using MySQL. It has all the functionalities with a full-featured Graphical User Interface (GUI). 

Abstract: The application was built long years back and gained a lot of popularity within a few months. The game starts with a snake whose size increases with the no of apples eaten by it and the life of the snake ends when it gets collided with a wall or any kind of hurdle which comes in the way. So, basically, the more apple snake eats, the more score you get. The navigation is like a snake can turn left or right by ninety degrees. A constructor can be used to start the movement of a snake and a function to perform various other operations. 

Technologies Required: Java, MySQL Database, JDBC, Java AWT, J-Frame, and Java Swing.

29. Job Portal in Java 

One thing which comes to your mind when you complete your graduation is getting a job. So, building a job portal for individuals where after entering the qualifications, the user gets the opportunity to enroll himself/herself for the job preferred. 

Abstract: The main objective of the online job portal project in java is to make the right job available for the right candidate. The admin, the recruiter, and the user are the three most vital parts of this application. Here, as soon as you enter the details or qualifications pursued by you, the recruiter verifies it and takes the further procedure ahead. The process includes verifying the details, contacting the concerned person, having all the interviews done, and receiving an offer letter. The database (which can be MongoDB) stores the data of the user. The user performs CRUD operations and deletes the profile as soon as the user gets a job. 

Technologies Required: Java, HTML, CSS, JavaScript, JSP, Java Servlet, MySQL Database, and Tomcat server.

30. Online Cab Booking System 

Ola and Uber are the online cab booking system that almost every one of us has become used. So building such a Java application would be the best idea. 

Abstract: In this project, the main objective is to help customers in booking a cab to reach their destination with pick-up as their preferred location. The application fetches your pick-up location and asks you to enter the drop location, when entered, finds a cab driver nearby and even tells you the calculated time the cab will take to drop you at the location. The system is designed using Spring MVC, Servlets, Hibernate, JDBC, JSP, HTML, and CSS. 

Technologies Required: Java, HTML, CSS, JavaScript, JSP, JDBC, Java Spring, Java Servlet, MySQL, and Tomcat Server.

31. Crime Records Management System

Based on the number of crimes being committed, this crime record management system is a secured application built using Java. It allows you to keep a record of the entries made of the number of crimes being committed. 

Abstract: This Java-based web application runs on a Tomcat server and uses MySQL as a database. Its main features include managing crimes, Handling FIRs, records of criminals, and complaints registered. You can develop a secured application using EJB, Spring, and Hibernate. You need MySQL database to run this project and MySQL J-Connector to make connections between MySQL and Java. 

Technologies Required: Java, JSP, JDBC, MySQL, and Tomcat Server.

32. Color Hunt Gaming Project

This Java-based gaming application is a mind game consisting of differently-colored letters which are randomly arranged. It is a kind of mind game that is built with the intention to increase your thought process. 

Abstract: Basically, in this game, there are different colors printed on the text, whatever statement gets displayed, you have to click on the mentioned color. As soon as you click on one, the other comes suddenly. You lose points when you don’t click on the color displayed. There’s also a time limit given in which you have to reach a given number of points. This game is built in such a way that it can only be played on android phones.  

Technologies Required: Java, Android, and XML.

33. Online CV/Resume Builder

You’re ready to apply for a job but don’t have an interesting CV/which perfectly shows your skills and qualifications. Online CV/Resume Builder comes to the rescue where just by entering required details you’ll get your CV/Resume in pdf format which is auto-generated. 

An online resume builder project is an internet-based application that can help students and other professionals to get an instant resume template, which they can fill easily with their credentials. An online resume builder provides different standard templates that can be downloaded in different formats like PDF and others. A user will not have to spend a lot of time on formatting and designing his or her resume. He will only enter his particulars and download his CV on the go.

Abstract: The online resume/cv builder application helps job seekers to build a CV with a proper format. It has different templates to choose from wherein you can opt for the best one. This application contains various modules which are user, skills, job, salary, and resume. Using these modules, different sections of a CV are made and after entering the details you get a properly organized CV.

Technologies Required: Java, MySQL Database, JDBC, Java Servlet, JSP, and Tomcat Server.

34. Weather Information System

This application tells you the weather-related information about your location and also of other locations. This Java-based application can be the best project for your minor project submission.

Abstract: Due to the change in weather, we can predict whether it’s going to be a rainy day, sunny day, or cold day. But sometimes, all of a sudden you see climate change. With the help of a weather information system which is a Java-based project, you can get to know the temperature not only your but also worldwide. The application picks up the default location and displays the weather data report. It tells you the temperature, rain, humidity, and even the direction of the wind blowing. 

Technologies Required: Java, Java Servlet, J2EE, Tomcat Server, HTML, CSS, and JavaScript.

35. Exam Seating Arrangement System

Exam Seating Arrangement System, the application implemented using JSP, Java, and MySQL. This application will help the examination handling manager to organize the allocation of seats for all the students. 

Abstract: This application takes in the details of the students be it name, roll no, section, branch, or year and stores it in databases. The admin is held responsible for managing the details, here the application is made to automate the seats allocates to students and this final list goes out on the day of examination which helps in not getting the seats revealed prior. The modules existing here are the student module, admin module, and seat module. This automated system helps in maintaining the record and proper functioning of the system.

Technologies Required: Java, HTML, CSS, JSP, JavaScript, MySQL, and Tomcat Server.

36. Traffic Controller System

The Traffic Controller System is a Java JSP and MySQL-based project, which is developed for process automation of the Traffic Controller System.

Abstract: The objective of this application is to create a system that controls the traffic which is done by implementing a set of classes and interfaces. The main features can be traffic lights, routes, diversions, and traffic police. It is a secured application that runs in the JVM. A GUI is created using JavaFX and classes for performing different operations such as the structure of the traffic network, and the main view of the system. The simulation is carried out to handle input and events that are being executed. 

37. Disaster Management System

Disaster Management System is a Java-based application that identifies and implements techniques for reducing the causes of the disaster and the losses faced. It can be the best project to avoid natural disasters. 

Abstract: Applications like this have four stages: mitigation, readiness, response, and recovery. Each process aims to reduce the risks occurred due to natural disasters like earthquakes, tsunamis, etc. The process follows when there’s a report submitted by the affected region, the data is collected and reported to the concerned authority to take measures. It is a web-based Java Swing project which stores data in MySQL for future references. The UI can have a login page, lists of earthquakes that happened, a new user page, and a user list. 

Memory Game – Flipping Tiles

Technologies Required: Java, Java Swing, JSP, JDBC, MySQL, and Java Servlet.

38. I-D Card Generator System

ID Card Generator System is a web-based Java project which uses the Swing library. It generates an ID of the entered details of the individuals and gives you a copy of it. 

Abstract: Application like this can be used in schools and offices where you require an ID card to enter the premises. In this project, you just need to log in and enter your personal details like name, age, blood group, designation, and the joining date, when you enter the required details, you get a copy of the ID card. The features can be storing the data in the database, having a unique identification number assigned to each individual, and no forgery allowed. 

Technologies Required: Java, Java Servlet, Java Swing, JSP, HTML, CSS, JavaScript, JDBC, MySQL, and Tomcat Server.

39. Memory Game – Flipping Tiles

Memory Game is a mind game where you have to remember the position of tiles placed earlier and re-assign them within the stipulated time. This game is implemented to play with your mind and bring the best.

Abstract: This Java-based gaming application is built using Swing. This game’s intention is to test our memory, here, we see an even number of tiles in which each number has a pair. All the tiles are kept facing downwards, all the tiles have to be flipped one by one, and when two tiles get matched they are removed from the tile. When there’s no match, the tiles are kept back in position. 

Technologies Required: Java, Java Swing, Java OOPS, and ArrayLists in Java.

40. Chat Application

Chat application has gained great popularity among individuals these days. This is similar to Instagram, Facebook, and Orkut. 

Abstract: This online chat application using Java uses graphical components in the Swing toolkit in Java and uses MySQL as a database. Its features include signing up, signing in, chatting, sending and accepting requests, and creating groups. You can also create a free account. It also checks whether there’s any fake account and gives no access to the user. 

Technologies Required: Java, Java Swing toolkit, MySQL, Java AWT, and JDBC. 

Advanced Level Java Projects Ideas

The below-given list consists of some advanced-level Java project ideas which can be used as major projects by the students or professionals.

41. Social Networking Site

Social Networking Site has gained a lot of popularity among individuals. It is Java JSP and MySQL project, running on the tomcat server. The management of users, photos, and videos are taken care of by this system. 

Abstract: The application has many features including a login page, a home page displaying all the posts by friends added to your account, a notification page displaying all the alerts, and a profile page where you can edit the details, and also upload a picture of yours. It uses HTTP requests to complete the operation which is being sent to the server. The process that the server follows is decoding the request, authenticating the user, and making changes to the database. JSON is used here to encode the result if found anything other than boolean.

Technologies Required: Java, Maven, J2EE, HTML, CSS, Java Servlet, JDBC, MySQL, and Tomcat Server.

42. Bug Tracking System

A system that keeps track of bugs that occurred during the development of a project. This Java-based application is created to help developers to manage bugs/errors occurring during SDLC. 

Abstract: Bug Tracking System is an application that focuses majorly on tracking the bug and changing its status. When the developer gets the help of a bug tracking system, he/she gets an assistant to help him/her during SDLC. The modules present in this can be the developer, admin, and management modules. The system records all the bugs in their detail so that the developer can work on them one by one. 

Technologies Required: Java, JDBC, JNDI, Servlets, JSP, Oracle/Access, RetHat JBoss AS, JavaScript, HTML, and CSS.

43. Text Editor in Java

Text Editor built using Java is similar to a notepad application. You can also create text documents and the system gives you the feature to edit the text entered in it. 

Abstract: A Text Editor built using Java uses JTextArea, JMenu, JMenuItems, and JMenuBar to perform various tasks. It allows the user to enter, change, store, and print text. It also has a file menu to make changes in files (like open, save, close, and print) for future references. and an edit menu to cut, copy and paste texts. Also, it has a “Save and Submit” button to close the file after saving the data. An actionListener is also used to detect actions in the project. 

Technologies Required: Java, Java Swing, Java AWT, JTextArea, JMenuBar, JMenu, and JMenuItems.

44. Digital Steganography

Security is a major concern be it in organizations, military, hospitals, schools, etc where data plays an important role. Keeping the data secure is much needed and here is a Java-based project for advanced programmers which is digital steganography. 

Abstract: Digital Steganography is the process in which data is sent from one point to another without affecting other users and also keeps the data secure. It uses multimedia as a covering medium. It embeds the text or image and stores it in the least significant bits of the image. It doesn’t even create suspense for the hackers. This is the best project advanced programmers on Java can work on. It contains both sender and receiver side programs to let the user choose whether to send or receive data. 

Technologies Required: Java, Java Servlet, MySQL or Oracle Database, JDBC, TomCat Server, JSP, HTML, CSS, and JavaScript.

45. Criminal Face Detection System

The Criminal Face Detection System application is built to detect the faces of criminals by matching them with the pre-existing data in the database. Although, there are so many ways to identify a criminal this could be the best way, and also building this project for advanced programmers is easy.

Abstract: The project is intended to use the images previously taken and identification will be done according to images taken of different people. This project aims to build an automated CFD system by levering the human ability to recall minute details in the facia. The criminal Face Detection System project aims to build a Criminal Face Detection system by levering the human ability to recall minute facial details. Identification of criminals at the scene of a crime can be achieved in many ways like fingerprinting, DNA matching, or eyewitness accounts. Out of these methods, eyewitness accounts are preferred because it stands scrutiny in court and it is a cost-effective method. It is possible that witnesses to a crime have seen the criminal though in most cases it may not be possible to completely see the face of the perpetrator.

Tip: We can also get this project done in Python language even better because of help of existing present libraries out there namely numpy and other tools: Keras. It will be easier to do in python language but doing via java makes one crystal clear about networking, machine mearning and java aplllciation onboard running concepts clear.  
Technologies Required: TensorFlow, Core java, Machine learning, SQlite, OpenCV(eccentric tool), Strong knowledge of advanced java concepts.

Criminal Face Detection System Java Project

46. Airline Reservation System with Advanced Features

With the increase in modernization, everything has come online. This application helps customers book flight tickets by just being at their comfort place and also searching for the availability, and timing of the flight. 

Abstract: To ease and automate the registration process system provides information like passengers information and a criminal list of all passengers. The software consists of 4 modules: User registration, login, reservation, and cancelation. The project includes online transaction fares, inventory, and e-ticket operations. Do remember not to mix it with Library Management System as here we have to go to and perform something where here it is a process. Yes, it seems easy on the skills side as mentioned below which are required.

Prerequisites Required: By far we are aware of Applets, Servers, Servlets, AWT, and Core Java concepts already with Collection Framework. 
Technologies Required- Core Java, Java Swing, Java AWT, Java Applet, Database-MySQL    

47. Advanced Chatting Application 

When everything has come online, chatting is also performed online be it your online friends or anyone. Hence, this advanced chatting application has advanced features like smooth communication with video and audio call facilities, and many more.

Abstract: There is not only one system rather we dop have multiple systems connected together. Client and Server communication takes place instead of basic request-based communication. This application will need to communicate through Sockets . The server and client can run on different computers in the same network. There can be multiple clients connected to a server and they can chat with each other. These days with every application, we are having a feature ‘Help’ to chat with a bot right from traveling apps such as Ola, and Uber to food apps such as Zomato, and Swiggy, this chatbox is embedded in every.   

Sockets are something new that one has to learn here in adhering to the advancement of the project because they will be used for networking, and TCP/IP protocols so communication can be built.  

Technologies Required: Core Java, Java Network-based libraries, Java Sockets, File handling, and Exception Handling.

Socket programming In Java

48. Customer-Relationship Manager 

It is a bit tedious but an easy pick among advanced-level java projects. It is also one of the most important projects as CRN is used by nearly all organizations, institutions,s or any software company as well to keep updated with the records. Do not confuse it with working just with awt and core java, as here we need to fetch it over a larger dataset in real-time for which we need to inculcate tools like Hibernate, MVC, CSS, JDBC, etc. Do create in a high-tech way invoking the above tools so that internal working of such tools can be perceived.

Abstract: It is the easiest of all projects at the advanced level as the name suggests that we have to build an application where we will be building relationships with customers by adding new customers in software, editing, and deleting the info whenever needed. The customer relations manager will keep track of all the customers. Adding new customers, editing their information, and deleting them when needed. Fetching already recorded customer details whenever required. 

Technologies Required: Spring Framework, Hibernate, HTML, CSS, JDBC, CRUD, MVC, and DB(MySQL) 

49. Email System

A great medium to conversate in an official way is through e-mails. Email system implemented using Java is of great value to organizations. So, advanced programmers can focus on the implementation of this project 

The project functions something like this – the ISP’s (Internet Service Provider) mail server handles the emails sent from an ISP. All the sent emails first come to the mail server, after which they are processed and forwarded to the collector’s destination where another mail server is located.

The mail server on the collector side receives the incoming emails and sorts them electronically in the inbox. Now, the recipient can use their email application to view the received emails. The entire transaction occurs by directly connecting to the mail server through the program, which makes it much safer than the existing email client software.

Abstract: This Email System is designed for sending and receiving emails for official communication which has a proper format. This system can use HTTP port 80 to access emails, also the two main protocols which can be used are SMTP (Simple Mail Transfer Protocol) and POP3. Java mail API can be used to transfer data. The ISP mail server receives all the mail sent, processes it, and then forwards it to the destined address. 

It is one of good project ideas among advance level project as it is of hard nut among projects we have discussed above and it will take a lot of time to properly build it. 

Technologies Required: Event Handler, HTTP, Protocols (like SMTP and POP3), 

50.  Advance Sudoku Game 

Sudoku Game is something which almost every one of us must have played. This game is all related to logic-building so once you play this, it gets easy for you to build logic so building this application is of great use.

Abstract: Building the same common sudoku game but with help of JavaFX. Generating a new game from a solution, keeping track of user input. Checking user input against the generated solution. Keeping track of selected numbers will be necessary for some of the functions and also the ability to check for errors and give hints in which we can invoke trained models from larger datasets from machine learning and artificial intelligence.    

Technologies Required: Core Java , Java FX , Event Listeners , MVC, Collection API

FAQs on Java Projects

Q.1 why use java.

Java is simple to learn programming language because doesn’t contain concepts like : Pointers and operator overloading and it is secure and portable.

Q.2 What is the difference between C++ and Java?

C++ JAVA C++ is platform dependent. Java is platform-independent. C++ uses a compiler only. Java uses a compiler and interpreter both. C++ support pointers and operator overloading. Java doesn’t support pointers and operator overloading concepts. C++ does not support the multithreading concept. Java supports the multithreading concept.

Q3: What are some good Java projects for beginners?

Here are the top 5 Java projects for beginners: Simple Calculator : Create a basic calculator application that performs arithmetic operations such as addition, subtraction, multiplication, and division. Address Book : Build an address book application that allows users to add, view, update, and delete contact information. Tic-Tac-Toe Game : Develop a simple console-based tic-tac-toe game where two players can take turns marking their moves on a grid. Hangman Game : Implement a text-based hangman game where players guess letters to reveal a hidden word. Temperature Converter: Design a program that converts temperatures between Fahrenheit, Celsius, and Kelvin scales. These projects are beginner-friendly and provide a solid foundation in Java programming concepts.

Q4: What kind of projects is Java used for?

Java is used for a wide range of projects, including web development, Android app development, enterprise software, big data processing, scientific computing, and financial applications.

Q5: Is Java worth learning in 2023?

Yes, learning Java in 2023 is highly beneficial due to its wide usage in enterprise applications, Android development, and strong community support. Java remains a valuable skill with abundant job opportunities and a versatile ecosystem.

Please Login to comment...

Similar reads.

  • 5 Reasons to Start Using Claude 3 Instead of ChatGPT
  • 6 Ways to Identify Who an Unknown Caller
  • 10 Best Lavender AI Alternatives and Competitors 2024
  • The 7 Best AI Tools for Programmers to Streamline Development in 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Java 8 Interview Questions and Answers ( Demonstrated with Live

    java interview case study

  2. 100+ Top Java Interview Questions and Answers in 2022

    java interview case study

  3. Java Interview Questions and Answers

    java interview case study

  4. Top 100 Core Java Interview Questions for Freshers

    java interview case study

  5. Java Interview Questions and Answers {Updated For 2023}

    java interview case study

  6. 100 most asked Java Interview Questions and Answers

    java interview case study

VIDEO

  1. Mastering Java Interview Questions: Common Challenges and Expert Answers

  2. Capgemini Interview

  3. Fresher Mock Interview JAVA

  4. How to attempt :Scenario/Case based JAVA programming in EXAMS

  5. What is a consulting case framework?

  6. How to transition from consulting to private banking w/ @talk2see

COMMENTS

  1. Review these 50 questions to crack your Java programming interview

    This list focuses on beginners and less experienced devs, like someone with 2 to 3 years of experience in Java. 1) How does Java achieve platform independence? ( answer) hint: bytecode and Java Virtual Machine. 2) What is ClassLoader in Java? ( answer) hint: part of JVM that loads bytecodes for classes.

  2. 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 ...

  3. 18 Java scenarios based interview Questions and Answers

    Full list of Java scenarios based interview questions are covered at Judging your Java experience via scenarios based interview Q&As. #1. Caching. Q01.Scenario: You need to load stock exchange security codes with price from a database and cache them for performance. The security codes need to be refreshed say every 30 minutes.

  4. 50 Java Interview Questions + 30 Scenario Based Q&A

    30 scenarios based interview questions and answers. 1. How will you find if a string contains only digits in Java? I can use matches () method of string to match the given string against a regular expression that matches digits like below: String str = "123"; boolean result = str.matches (" [0-9]+"); 2.

  5. 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.

  6. The complete guide to Java interview questions and interview prep

    Resources for common Java interview questions. To prepare for basic Java interviews, check out these resources: Java interview prep: 15 Java interview questions: Blog post covering questions from bytecode to platform independence; Exploring object-oriented programming concepts with Java: Blog post detailing object-oriented programming in Java

  7. 21 Essential Java Interview Questions

    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. is an exclusive network of the top freelance software developers, designers, finance experts, product managers, and project ...

  8. 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.

  9. Top 100+ Core Java Interview Questions

    Java Thread Interview Questions. Java Collections Interview Questions. Java Exception Interview Questions. Here I am providing some of the important core java interview questions with answers that you should know. You can bookmark this post to brush up on your knowledge before heading for an interview. 1.

  10. Pass the Technical Interview with Java

    Pass the Technical Interview with Java. Learn about the computer science concepts of data structures and algorithms and build implementations of each from scratch in modern Java. Includes Java, Interview Questions, Data Structures, Big O, Recursion, Sort and Search Algorithms, and more. Try it for free.

  11. Crack the top 40 Java coding interview questions

    Java remains a popular language across the world. Especially in financial fields, Java's scalability and efficiency keep it in-demand with interviewers in a variety of famous companies like Goldman Sachs, eBay, and Google.. Today, we'll help you prepare for your upcoming coding interview at these and other popular eCommerce companies by reviewing the top 40 Java questions asked by ...

  12. 49 Core Java interview questions for experienced programmers

    Here are 49 questions you can ask experienced candidates to evaluate their abilities and knowledge. 19 Core Java interview questions for experienced talent about technical knowledge. 5 Core Java interview questions for experienced programmers with sample answers. 10 Core Java interview questions for experienced talent about technical processes.

  13. Java Interview Preparation Guide

    You cannot skip this question if your resume says you work on Java 8. In the linked tutorial, I will show you the correct scenarios, which will help you crack some complex interview questions and case studies. 1.11. Enum interview questions. The enum has been a core building block for a long time. They can be seen in the most popular Java ...

  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. 300 Core Java Interview Questions (2023)

    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. The answers to the Core Java interview questions are short and to the point.

  16. Java Interview Prep: Top 5 Coding Problems

    Enhance your Java interview skills with this comprehensive guide on 5 essential coding problems. In-depth, detailed, step-by-step solutions included.

  17. Study Plan to Crack Java Interview with Java 8, Spring, Spring Boot

    Introduction: Preparing for a Java interview requires a structured study plan that covers key topics like Java 8, Spring Framework, Spring Boot, and Microservices. This comprehensive study plan ...

  18. Top 20 Core Java Interview Questions And Answers

    Core Java Interview Questions and Answers Real-time Case Study Questions ️Frequently Asked ️Curated by Experts ️Download Sample Resumes. All courses. All Resources. On-demand Webinars. Community. subscribe. Open Menu. Course Categories. AI and Machine Learning.

  19. Case Study interview for entry level Java developer position

    The case study is a software engineering case study. You are given a fake "request" from a manager for a piece of functionality. Then you explain your line of thinking in where you would go from there. Its really not that bad as long as you have learned the basics of software engineering, software quality, requirements testing, things like that ...

  20. List of Examples and Case Studies

    O'Reilly members experience books, live events, courses curated by job role, and more from O'Reilly and nearly 200 top publishers. List of Examples and Case Studies 2.1 Welcome 2.2 Drawing a flag 2.3 Curio Store 2.4 Displaying a warning 2.5 Curio shop table 2.6 Fleet timetables 3.1 Math class investigation …. - Selection from Java Gently ...

  21. Here's Why We Do Case Interviews for Software Engineers

    Case interviews are a format of interview that create a realistic scenario, allowing the candidate to apply the real skills they would need to be successful in our work. A case interview tests not just programming skills, but communication, estimation, and risk management. Perhaps most importantly, it tests for the ability to translate a ...

  22. Case Study in java

    Case Study in java. Ask Question Asked 13 years, 3 months ago. Modified 2 years, 11 months ago. Viewed 1k times -2 Could anyone provide me information where I can find the case study for java coding and design practice. ... An interview question in java. 2. Java design/implementation question. 0. Java related Lab/homework questions. 2. Looking ...

  23. Top 50 Java Project Ideas For Beginners & Advanced

    7. Library Management System. Learning Management System, this project build on Java is a great way to update the record, monitor and add books, search for the required ones, taking care of the issue date and return date. It comes with basic features like creating a new record and updating and deleting it.