• ▼Java Exercises
  • Basic Part-I
  • Basic Part-II
  • Conditional Statement
  • Recursive Methods
  • Java Enum Types
  • Exception Handling
  • Java Inheritance
  • Java Abstract Classes
  • Java Thread
  • Java Multithreading
  • Java Lambda expression
  • Java Generic Method
  • Object-Oriented Programming
  • Java Interface
  • Java Encapsulation
  • Java Polymorphism
  • File Input-Output
  • Regular Expression
  • ▼JavaFx Exercises
  • JavaFx Exercises Home
  • ..More to come..

Java Programming Exercises, Practice, Solution

Java exercises.

Java is the foundation for virtually every type of networked application and is the global standard for developing and delivering embedded and mobile applications, games, Web-based content, and enterprise software. With more than 9 million developers worldwide, Java enables you to efficiently develop, deploy and use exciting applications and services.

The best way we learn anything is by practice and exercise questions. Here you have the opportunity to practice the Java programming language concepts by solving the exercises starting from basic to more complex exercises. A sample solution is provided for each exercise. It is recommended to do these exercises by yourself first before checking the solution.

Hope, these exercises help you to improve your Java programming coding skills. Currently, following sections are available, we are working hard to add more exercises .... Happy Coding!

List of Java Exercises:

  • Basic Exercises Part-I [ 150 Exercises with Solution ]
  • Basic Exercises Part-II [ 99 Exercises with Solution ]
  • Methods [ 23 Exercises with Solution ]
  • Data Types Exercises [ 15 Exercises with Solution ]
  • Java Enum Types Exercises [ 5 Exercises with Solution ]
  • Conditional Statement Exercises [ 32 Exercises with Solution ]
  • Java recursive method Exercises [ 15 Exercises with Solution ]
  • Math [ 27 Exercises with Solution ]
  • Numbers [ 28 Exercises with Solution ]
  • Java Inheritance Exercises [ 9 exercises with solution ]
  • Java Abstract Classes Exercises [ 12 exercises with solution ]
  • Java Interface Exercises [ 11 exercises with solution ]
  • Java Encapsulation Exercises [ 7 exercises with solution ]
  • Java Polymorphism Exercises [ 12 exercises with solution ]
  • Object-Oriented Programming [ 30 Exercises with Solution ]
  • Exercises on handling and managing exceptions in Java [ 7 Exercises with Solution ]
  • Java Lambda expression Exercises [ 25 exercises with solution ]
  • Streams [ 8 Exercises with Solution ]
  • Java Thread Exercises [ 7 exercises with solution ]
  • Java Miltithreading Exercises [ 10 exercises with solution ]
  • Array [ 77 Exercises with Solution ]
  • Stack [ 29 Exercises with Solution ]
  • Collection [ 126 Exercises with Solution ]
  • String [ 107 Exercises with Solution ]
  • Input-Output-File-System [ 18 Exercises with Solution ]
  • Date Time [ 44 Exercises with Solution ]
  • Java Generic Methods [ 7 exercises with solution ]
  • Java Unit Test [ 10 Exercises with Solution ]
  • Search [ 7 Exercises with Solution ]
  • Sorting [ 19 Exercises with Solution ]
  • Regular Expression [ 30 Exercises with Solution ]
  • JavaFX [ 70 Exercises with Solution ]

Note: If you are not habituated with Java programming you can learn from the following :

  • Java Programming Language

More to Come !

Popularity of Programming Language Worldwide, Nov 2023 compared to a year ago:

`
Rank Change Language Share Trend
1 Python 27.99 % +0.0 %
2 Java 15.91 % -0.8%
3 Javascript 9.18 % -0.3%
4 C/C++ 6.76 % +0.2%
5 C# 6.67 % -0.3 %
6 PHP 4.86 % -0.3 %
7 R 4.45% +0.4%
8 TypeScript 2.95 % +0.1%
9 Swift 2.7 % +0.6%
10 Objective-C 2.32% +0.2%
11 Rust1.98% +0.3%
12 Go 1.98% -0.0%
13 Kotlin 1.76 % -0.1%
14 Matlab 1.6 % +0.0%
15 Ada 1.02% +0.2%
16 Ruby 1.0 % -0.1 %
17 Dart 0.99 % +0.1 %
18 Powershell 0.93 % +0.0 %
19 VBA 0.93 % -0.1 %
20 Scala 0.62 % -0.1 %
21 Lua 0.62 % 0.0 %
22 Abap 0.58 % +0.1 %
23 Visual Basic 0.55 % -0.1 %
24 Julia 0.35 % -0.0 %
25 Groovy 0.31 % -0.1 %
26 Perl 0.31 % -0.1 %
27 Haskell 0.27 % -0.0 %
28 Cobol 0.25 % -0.1 %
29 Delphi/Pascal 0.18 % +0.2 %

Source : https://pypl.github.io/PYPL.html

TIOBE Index for November 2023

Nov 2023 Nov 2022 Change Programming Language Ratings Change
1 1 Python 14.16% -3.02%
2 2 C 11.77% -3.31%
3 4 C++ 10.36% -0.39%
4 3 Java 8.35% -3.63%
5 5 C# 7.65% +3.40%
6 7 JavaScript 3.21% +0.47%
7 10 PHP 2.30% +0.61%
8 6 Visual Basic 2.10% -2.01%
9 9 SQL 1.88% +0.07%
10 8 Assembly language 1.35% -0.83%
11 17 Scratch 1.31% +0.43%
12 24 Fortran 1.30% +0.74%
13 11 Go 1.19% +0.05%
14 15 MATLAB 1.15% +0.14%
15 28 Kotlin 1.15% +0.68%
16 14 Delphi/Object Pascal 1.14% +0.07%
17 18 Swift 1.04% +0.17%
18 19 Ruby 0.99% +0.14%
19 12 R 0.93% -0.20%
20 20 Rust 0.91% +0.16%

Source : https://www.tiobe.com/tiobe-index/

List of Exercises with Solutions :

  • HTML CSS Exercises, Practice, Solution
  • JavaScript Exercises, Practice, Solution
  • jQuery Exercises, Practice, Solution
  • jQuery-UI Exercises, Practice, Solution
  • CoffeeScript Exercises, Practice, Solution
  • Twitter Bootstrap Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution
  • C# Sharp Programming Exercises, Practice, Solution
  • PHP Exercises, Practice, Solution
  • Python Exercises, Practice, Solution
  • R Programming Exercises, Practice, Solution
  • Java Exercises, Practice, Solution
  • SQL Exercises, Practice, Solution
  • MySQL Exercises, Practice, Solution
  • PostgreSQL Exercises, Practice, Solution
  • SQLite Exercises, Practice, Solution
  • MongoDB Exercises, Practice, Solution

[ Want to contribute to Java exercises? Send your code (attached with a .zip file) to us at w3resource[at]yahoo[dot]com. Please avoid copyrighted materials.]

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics

Javarevisited

Learn Java, Programming, Spring, Hibernate throw tutorials, examples, and interview questions

Topics and Categories

  • collections
  • multithreading
  • design patterns
  • interview questions
  • data structure
  • Java Certifications
  • jsp-servlet
  • online resources
  • jvm-internals

Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Tuesday, March 26, 2024

  • Top 50 Java Programs from Coding Interviews

Java Programming Interview Questions for 2 to 3 years

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

Ace the top 15 Java algorithm questions for coding interviews

Become a Software Engineer in Months, Not Years

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

Algorithm-based questions are a staple of any modern coding interview, as they demonstrate your problem-solving and critical thinking skills. To make sure you don’t get caught off guard in your next Java interview, we’ve put together 15 of the most common algorithm coding questions used by most tech companies and recruiters across the industry.

These algorithm coding questions vary in difficulty, so if you can’t figure out one don’t be ashamed to move on to the next and return later. With enough practice, you’ll shortly be able to crack any interview question thrown at you. Each question is followed by a detailed explanation to help you get prepped for the big interviews ahead.

Today we’ll be covering questions on:

Measuring Complexity: Big O Notation

Sorting and searching: quicksort, binary search and more.

Dynamic Programing: Memoization and Tabulation

Greedy Algorithms: Maximization

Divide and Conquer

Graph Algorithms

Master Java coding interview patterns with our hands-on course today.

Cover

Finally, we add all lines’ time complexity, drop the leading constants and lower order terms, and find our Big O Complexity.

Almost ever interviewer will ask a question which calls for at least one type of searching or sorting, if not more. To help you prepare for these questions, we’ve included the following overview section to build foundational search/sort algorithm proficiency.

Note: It’s unlikely you’ll be prompted to use a certain algorithm in an interview. Instead, you must learn to recognize which algorithm to use based on keywords in the problem statement. As you practice, try to pinpoint which part of the problem statement would lead you to use the indicated algorithm.

2: Quicksort

Given an unsorted array of numbers, find K th smallest number in it.

Please note that it is the K th smallest number in the sorted order, not the K th distinct element.

Time Complexity: average O ( N ) O(N) O ( N ) or worst case O ( N 2 ) O(N^2) O ( N 2 )

We use Quicksort’s partitioning scheme to find the Kth smallest number. We recursively partition the input array and if, after partitioning, our pivot is at the K-1 index we have found our required number. If not, we choose one the following options:

  • If pivot’s position is larger than K-1, we recursively partition the array on numbers lower than the pivot.
  • If pivot’s position is smaller than K-1, we recursively partition the array on numbers greater than the pivot.

3: Binary Search

We are given a 2D array where all elements in any individual row or column are sorted. In such a matrix, we have to search or find the position of, a given key.

Time Complexity: O ( m + n ) O(m + n) O ( m + n )

We start from the upper right corner of the matrix and compare its value with the key. If they are equal, we have found the position of the key.

If the key is smaller than the current element, we move to the left one position. If the key is larger than the current element, we move right one position.

As the matrix is sorted, moving left always results in lower values than the current while moving down always results higher values. We continue this process until either we find the element or go out of the boundary of the matrix (which indicates that the key does not exist).

4. Merge Sort

Given the head pointer of a linked sort, sort the linked list in ascending order using merge sort, and return the new head pointer of the sorted linked list.

Time Complexity: O ( n l o g n ) O(nlogn) O ( n l o g n )

In the dividing step, we split our input linked list into two halves and keep doing so until there is a linked list of size 1 or 0. Linked lists of size 1 and 0 are always sorted. In the combining step, we merge sorted lists and keep doing so until we have a completely sorted list.

At each step, we divide our problem into two sub-problems. The size of each sub-problem is n 2 \frac n2 2 n ​ and the total cost of combining steps (merging sorted lists) is n n n .

5. Insertion Sort

Given the head pointer of a linked list, sort the linked list in ascending order using insertion sort. Return the new head pointer of the sorted linked list.

Time Complexity: O ( n 2 ) O(n^2) O ( n 2 )

While the original list is not empty:

Remove an element (say ‘X’) from the original list.

Insert ‘X’ at the correct sorted position in the sorted list.

To insert a node into the sorted linked list, we may need to scan the entire sorted list depending upon the node being inserted.

Using a HashMap, implement a function that takes an array arr , a number value , and the size of the array as an input and returns two numbers that add up to value .

Time Complexity: O ( n ) O(n) O ( n )

For all the elements in the arr array, we store the difference n - arr[i] in hmap .

Then with another iteration over arr , we check if any element of arr exists in the hmap , which means the difference of n and the number found ( n - arr[i] ) are also present.

Therefore, an array of size 2 called result is created to store the pair that sums up to n . If hmap contains an array element, result[] is updated, or else it is returned containing the default value.

Implement an isSubset() function to take two arrays as input and check whether an array is a subset of another given array.

Time Complexity: O ( m + n ) O(m+n) O ( m + n )

First, we iterate over arr2 and arr3 to see whether their elements can be found in arr1 .

At the back end, the values are checked against their hashed indices in arr1 .

Dynamic Programming: Memoization and Tabulation

Dynamic Programming is a central algorithm technique for the modern developer, as it focuses on breaking a problem into simpler sub-problems to achieve optimization. The more optimal the solution to sub-problems, the more optimal the overall solution is.

This is the foundation of recursive problem-solving and therefore will be asked by any good interviewer.

Dynamic Programming questions can either be solved from a Top-Down approach or a Bottom-Up approach, using either Memoization or Tabulation , respectively. Interviewers may ask for one or may leave it to your decision.

Below we’ll see an example of each so you’re prepared for any alternative.

8. The Knapsack Problem:

Imagine that you’re an adventurer with a knapsack looking over a dragon’s hoard.

Given two integer arrays that represent the weights and profits of N items, implement a function knapSack() that finds a subset of these items that will give us the maximum profit without their cumulative weight exceeding a given number capacity . Each item may only be selected once, which means when we get to it we can either skip it or put it in the knapsack.

Use the top-down approach with memoization.

Time Complexity: O ( N ∗ C ) O(N*C) O ( N ∗ C )

The function knapSack makes a lookupTable within the function that stores the maximum value that can be attained with maximum capacity (lines 29-35). This function calls the helper function knapsackRecursive (line 36). It returns the maximum value that can be attained using only the first i items, i.e., items at the currentIndex while keeping their total weight no more than weights.

We have two varying values ( capacity and currentIndex ), so we can use a two-dimensional array to store the results of all the solved subproblems in our recursive function knapsackRecursive .

We need to store results for every subarray, i.e., for every possible index and for every possible capacity. If the lookupTable[currentIndex][capacity] is already computed before (line 10), this value is immediately returned (line 11).

Otherwise, we call the function recursively:

With the item, saving the result in profit1 (line 17).

Without the item, saving the result in the variable, profit2 (line 21).

Out of the two, we return the result that is greater (as done on lines 23-24).

9. Staircase Problem

A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a function to count the number of possible ways that the child can run up the stairs.

Try to solve this one using a Bottom-Up approach with Tabulation.

We know that:

The total number of ways to reach the zero-step is 1 (line 6).

The total number of ways to reach the first step is 1 (line 7).

The total number of ways to reach the second step is 2 (line 8).

Hence, we fill up the lookupTable with these three values (lines 6-8).

We know that the total number of ways to reach any n th stair is by taking 1, 2, or 3 steps. Hence, the total number of ways to reach an n th stair would be equal to the sum of the total number of ways to reach [n-1] th step, number of ways to reach [n-2] th step, and the number of ways to reach the [n-3] th step.

So, the rest of the values of the lookupTable are filled by calculating the total number of ways to reach an nth step by summing the ways to reach the previous three steps (line 11).

The required value is then returned from the lookupTable (line 13).

Greedy Algorithms: Local Maximization

Greedy is an algorithmic technique where the solution is built one piece at a time, prioritizing immediate, obvious benefits at each choice. In other words, it seeks to maximize profit (the positive) and minimizes the cost (the negative).

This technique works on the idea that the locally optimal choice will contribute to the globally optimal solution. Below we’ll see a few interview questions to help you use this technique when required.

10: Change Machine Problem

You have to make such a change machine that only returns the change in the form of coins.

You are supplied with an infinite number of quarters (25 cents), dimes (10 cents), nickels (5 cents), and pennies (1 cent). The user will enter any amount. For each amount, you have to return the minimum number of coins possible!

Line 3: A public array is given containing the set of coins available.

Line 6: The function getMinCoins() is defined; it has ArrayList as its return type and int amount as its parameter.

Line 9: The ArrayList of type Integer is allocated to store the change.

Lines 10-17: A for loop traverses the int[]coins array from beginning to end (given in descending order).

Line 12: Since the first index of coins has the maximum element, compare in the while condition whether this amount is greater than the max coin.

Line 14: If yes, subtract the max value coin from the amount given.

Line 15: Add this coin to the change list.

Line 17: When the largest coin becomes greater than the remaining amount, the while loop breaks and the value of i is incremented to move to the next (lesser value) coin.

Keep iterating this for loop, until the remaining amount can no longer be subdivided by the available coins.

11: Find the Egyptian Fraction

Every positive fraction can be represented as the sum of its unique unit fractions. A fraction is a unit fraction if the numerator is 1 and the denominator is a positive integer. For example, 1 3 \frac 13 3 1 ​ is a unit fraction. Such a representation is called Egyptian fraction.

Time Complexity: O ( l o g 3 ) O(log_3) O ( l o g 3 ​ )

For a given number of the form n d \frac nd d n ​ , where d > n, first find the greatest possible unit fraction, and then perform recursion for the remaining part.

For example, consider 6 14 \frac 6{14} 14 6 ​ . We first find the ceiling of 14 6 \frac {14}6 6 14 ​ , i.e., 3, so the first unit fraction becomes 1 3 \frac 13 3 1 ​ . Now subtract 1 3 \frac 13 3 1 ​ out of 6 14 \frac 6{14} 14 6 ​ and recur for 6 14 \frac 6{14} 14 6 ​ – 1 3 \frac 13 3 1 ​ .

We use the greedy algorithm because we want to reduce the fraction to a form where the denominator is greater than the numerator and the numerator doesn’t divide the denominator.

The method is to find the biggest unit fraction we can and subtract it from the remaining fraction. Doing subtractions always decreases this group of unit fractions, but it never repeats a fraction and eventually will stop, which is why we call this approach greedy.

Divide and Conquer:

Similar to Dynamic Programming, Divide and Conquer algorithms work by breaking down a problem into sub-problems. Where they differ is that Divide and Conquer algorithms solve each sub-problem then combine the results to form the ultimate solution whereas the sub-problems in Dynamic Programming are fully separate.

This is another staple type of algorithm that will be tested in your coding interview.

12: Euclidean Algorithm Problem

Given two integers a and b , calculate the largest number (GCD) that divides both of them without leaving a remainder.

Time Complexity: O ( l o g m i n ( a , b ) ) O(log min(a,b)) O ( l o g min ( a , b ))

  • Line 5: The algorithm starts by checking if the first number ( a , which was obtained by b \%ab%a in recursive calls) is 0.
  • Line 6: If that is the case, then return b .
  • Line 7: Otherwise, we make the next recursive call GCD(b % a, a) .

13: Missing number in Sorted Array

Given an array of contiguous integers starting from x , with one missing integer in between, and the size of the array, find the missing number!

Time Complexity: O ( l o g n ) O(log_n) O ( l o g n ​ )

Line 38: The driver program calls the function missingNumber() with int [] arr and int size as its parameters.

Line 6: Initialize the right and left limits.

Lines 9-10: Handles corner case 1. Return 1 if array’s 1st element is not equal to 1.

Line 12-18: Begin by finding the middle index of the array, if the element at middle is not equal to middle + 1 , and this is the first missing element, middle + 1 is the missing element.

Lines 21-26: If this is not the first missing element and arr[middle] is not equal to middle+1 , search in the right half. Otherwise, search in the left half of the array.

Line 28: Handles corner case 2. Return -1 if you end up traversing the whole array and no element is missing.

Graphs Algorithms:

For our final section we’ll look at problems to build proficiency with common graph-related questions. These questions are becoming increasingly popular in interviews due to their prevalence in social-media mapping, meaning now more than ever it’s key to come prepared with this practice.

14: Calculate the Number of Nodes in a Given Graph Level

Implement a function that returns the number of nodes at a given level of an undirected graph.

Time Complexity: O ( V + E ) O(V + E) O ( V + E )

The solution above modifies the visited array to store the level of each node. Later, it counts the nodes with the same level (lines 32-35).

In this code, while visiting each node, the level of the visited node is set with an increment in the level of its parent node, i.e.,

This is how the level of each node is determined (line 26).

15: Transpose a Graph

Implement a function that takes a directed graph as input and print its transpose.

First, you make another graph and start reversing it. Traverse the adjacency list of the given graph. When the program finds a vertex v in the adjacency list of vertex u (i.e., an edge from u to v in the given graph), add an edge from v to u in the transposedGraph , adding u in the adjacency list of vertex v of the new graph) (lines 9-13).

In line 19, the printGraph() function prints the graph to console. You can find its implementation in Graph.java file (lines 29-36).

More coding interview questions to ace algorithms:

  • Search in a rotated array
  • Find the median of two sorted arrays
  • Find duplicates in an array
  • The Dutch National Flag Problem
  • Find the longest common substring in a string
  • The Egg Drop Problem
  • Find the longest palindromic subsequence of a string
  • The Edit Distance Problem
  • Connect n pipes with the minimum cost
  • The Train Station Platform Problem
  • The Fractional Knapsack Problem
  • Find Kruskal’s minimum spanning tree
  • Find the peak element in an array
  • Shuffle the integers of an array
  • Search a graph breadth-first
  • Search a graph depth-first
  • Count the paths between two nodes
  • Print all connected components in a graph
  • Remove an edge of a graph
  • Implement topological sorting of a graph
  • Check if a graph is strongly connected
  • Check if a graph is Bipartite
  • Find the floor and ceiling of a number
  • Find the closest number in an array
  • Collect coins in the least steps
  • Find the maximum sum of two subarrays
  • The Coin Change Problem
  • The Partition Problem
  • Count element occurrence
  • The Sparse Search Problem

Where to go from here

Great work! Hopefully, you can already feel that pre-interview anxiety starting to melt away. While this was a deep dive into 15 of the most common algorithm questions, there are many more possibilities that may come up during your interview. Varied practice is essential to success in any coding interview.

If you want to practice your Java coding skills, then Educative-99 or Educative-77 in Java are the perfect places to go. Educative-99 is curated by expert developers for beginner developers in order to help them ace their Java coding and algorithm skills.

To master the underlying patterns behind coding interview problems, check out our course, Grokking Coding Interview Patterns in Java .

Interview roadmap

If you’re unsure where the road to your dream front-end dev job leads next, take a look at our free interview roadmap to help you get quickly.

Keep reading about interview prep

  • 5 tried and true techniques to prepare for a coding interview
  • Cracking the top Amazon coding interview questions

Learn in-demand tech skills in half the time

Mock Interview

Skill Paths

Assessments

Learn to Code

Tech Interview Prep

Generative AI

Data Science

Machine Learning

GitHub Students Scholarship

Early Access Courses

For Individuals

Try for Free

Gift a Subscription

Become an Author

Become an Affiliate

Earn Referral Credits

Cheatsheets

Frequently Asked Questions

Privacy Policy

Cookie Policy

Terms of Service

Business Terms of Service

Data Processing Agreement

Copyright © 2024 Educative, Inc. All rights reserved.

Java-interview-questions-and-answers

Java Interview Questions and Answers

Adam-Carpenter.png?w=288

  • Share article on Twitter
  • Share article on Facebook
  • Share article on LinkedIn

The pressure to perform well in an interview can feel overwhelming. Despite your knowledge and experience, nervousness could get in the way of putting your best foot forward. But, if you know the questions to expect and how to answer them, you can relax and focus on showcasing what you know and what you can do.

To help you prepare, we’ve compiled this list of common Java interview questions. We’ll explore a few questions for beginner, intermediate, and experienced Java developers, explain how to answer them, and show you what additional steps you can take to nail your interviews.

Beginner Java interview questions

Beginner Java interview questions are designed to test your knowledge of basic Java principles and methods. Here are some common questions and their answers.

What makes Java different from some other programming languages?

  • Distributed
  • Multithreaded
  • Object-oriented
  • Platform independent

What is “inheritance” in Java?

Inheritance is a core principle in object-oriented programming. It allows an object to inherit the properties of a different class. The class the properties are inherited from is known as the superclass, and the one that inherits the properties is the subclass.

What are the foundational principles related to object-oriented programming?

  • Polymorphism
  • Abstraction
  • Inheritance
  • Encapsulation

Intermediate Java interview questions

Intermediate Java interview questions are meant to see if you both understand and know how to apply some of the essential Java principles and tools. Below are some of the more common mid-level Java interview questions.

Describe the Spring framework

The Spring framework is used to make enterprise applications using Java. Its central features can work with essentially any Java application.

Spring is an application framework and container that facilitates the inversion of control (IoC). With inversion of control, a generic network sends the flow of control to customized portions of a program.

How does session management work within servlets?

A session includes the exchange of information between the server and client. These conversations can be managed using:

  • Cookie applications
  • A session management application programming interface (API)
  • Session IDs included in the discourse between the server and the client
  • URL rewriting and HTML hidden fields

How is the JDBC ResultSet Interface used?

The ResultSet Interface is used to represent a row in a table. You can also use it to change the cursor and process information from a database.

Experienced Java interview questions

Experienced Java interview questions assess your knowledge of the language’s inner workings and advanced features. Here are some common questions you may get asked if the position requires a more experienced Java programmer.

How are “= =” and “equals ()” different?

“==” is the equality operator, and you use it to compare objects and primitives. On the other hand, “equals ()” checks whether two objects are equal within the business logic process.

How does garbage collection work in Java?

Garbage collection is used when an object is either not being referenced or isn’t being used. At that point, garbage collection can automatically destroy the object.

Describe what makes a queue and a stack different

A stack is based on the principle of Last In, First Out (LIFO). A queue is different in that it’s based on the First In, First Out (FIFO) principle.

What is the base class of all exception classes in Java?

The base class of all exception classes is Java.lang.Throwable. This being the base class means that all exception classes are derived from it.

What are the differences between the static and non-static methods?

With the static method, the static keyword has to precede the method name, and you call it using the class, as in “className.methodName.” Also, you can’t access any non-static methods or instance variables with the static method.

The non-static method doesn’t require you to use a static keyword before the method name, and you can call it as you would any general method. And, the non-static method can access any other static method and variable without the need to rate an instance of the class.

Describe constructor chaining

Constructor chaining in Java involves calling a constructor from another in connection with the current object. To make this happen, a subclass constructor has to be able to invoke its constructor first.

The constructor chaining process can be accomplished either within the same class using “this()” or from the base class by using “super().”

What is referred to by the term “classloader”?

ClassLoader is a subset of Java Virtual Machine (JVM), and it loads class files. When a Java program gets executed, the ClassLoader is what loads it.

Java provides you with three different classloaders:

  • Extension ClassLoader
  • Bootstrap ClassLoader
  • System/Application ClassLoader

Refreshing your knowledge and next steps

The questions above provide a solid foundation for your upcoming interviews, but if you’re still feeling unprepared, there are several steps you can take. We offer a wide range of Java courses you can use to refresh your knowledge of the language’s features and take your skills to the next level. Java is one of the most widely used and versatile languages, and you can learn how to use it with courses and Skill Paths like:

  • Build Basic Android Apps with Java
  • Pass the technical Interview with Java
  • Create REST APIs with Spring and Java

Plus, with our Skill Paths, you’ll also get the chance to build an impressive portfolio that you can use to showcase your Java skills.

As you learn with us, you’ll connect and interact with other developers and discover new ways to use Java. Equipped with the knowledge, experience, and projects you’ll gain in your courses, you can impress your interviewer and clearly illustrate your value to the organization. To get started, you can sign up with us today, free of charge .

problem solving question in java

Related articles

What-soft-skills-are-and-how-to-showcase-them-1.png?w=1024

What Soft Skills Are & How to Showcase Them

Soft skills don’t receive as much attention as hard skills, but they’re just as important. Learn how to showcase your soft skills during the hiring process.

The-Most-Important-Soft-Skill-for-Developers-—-How-to-Get-Better-at-It.webp?w=1024

The Most Important Soft Skill for Developers & How to Get Better at It

Try these problem-solving strategies the next time you’re feeling stuck.

ProskilllaunchBlog_SM_F_TKExamplesofInterpersonalSkillsThatYouNeedinTechCareers-ezgif.com-jpg-to-webp-converter.webp?w=1024

The Interpersonal Skills That You Need in Tech Careers

Work is more than just contributing code — these people skills make you stand out.

ProskilllaunchBlog_SM_F_TKPhrasesThatMakeYouaBetterCommunicator-ezgif.com-jpg-to-webp-converter.webp?w=1024

6 Phrases That Make You a Better Communicator

Techniques and tips for your communication skill set. 

How-Much-Does-A-Java-Developer-Make_Thumbnail.png?w=1024

How Much Does A Java Developer Make?

Curious how much you can earn as a Java Developer? We break down the factors that can influence your salary in the Java development field.

Featured-Thumbnails_1200x558-1-1.png?w=1024

10 Java Code Challenges for Beginners

Are you learning Java and looking for exercises to test your new skills? Try these 10 Java code challenges for beginners and put your Java knowledge to use.

Featured-Thumbnails_1200x558-3-1.png?w=1024

10 Advanced Java Code Challenges

Code challenges are a great way to improve your coding skills. Try these 10 advanced Java code challenges to put your Java programming knowledge to the test.

Javatpoint Logo

Java Tutorial

Control statements, java object class, java inheritance, java polymorphism, java abstraction, java encapsulation, java oops misc.

JavaTpoint

Java is a popular programming language that is used to develop a wide variety of applications. One of the best ways to learn Java is to practice writing programs. Many resources are available online and in libraries to help you find Java practice programs.

When practising Java programs, it is important to focus on understanding the concepts behind the code. Don't just copy and paste code from a website or book. Try to understand why the code is written the way it is. It will help you become a better Java programmer.





Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

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

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

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

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

Learn Java and Programming through articles, code examples, and tutorials for developers of all levels.

  • online courses
  • certification
  • free resources

Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Top 53 Java Programs for Coding and Programming Interviews

50+ java coding problems from programming job interviews.

Top 50 Java Programs from Coding and Programming Interviews

  • 10 Courses to Prepare for Programming Interviews
  • 10 Books to Prepare Technical Programming/Coding Job Interviews
  • 20+ String Algorithms Interview Questions
  • 25 Software Design Interview Questions for Programmers
  • 20+ array-based Problems for interviews
  • 40 Binary Tree Interview Questions for Java Programmers
  • 10 Dynamic Programming Questions from Coding Interviews
  • 25 Recursion Programs from Coding Interviews
  • Review these Java Interview Questions for Programmers
  • 7 Best Courses to learn Data Structure and Algorithms
  • 10 OOP Design Interview Questions with solution
  • Top 30 Object-Oriented Programming Questions
  • Top 5 Courses to learn Dynamic Programming for Interviews
  • 10 Algorithm Books Every Programmer Should Read
  • Top 5 Data Structure and Algorithm Books for Java Developers
  • 100+ Data Structure and Algorithm Questions with Solution
  • 75+ Coding Interview Questions for 2 to 5 years experience
  • 10 Programming and Coding Job interview courses for programmers

good questions, thanks

Feel free to comment, ask questions if you have any doubt.

Devglan Logo

  • Java Interview Programming Questions and Answers

java-programs thumbnail

Java is an object-oriented programming language and computing platform first released by Sun Microsystems in 1995.

During an interview it does not matter whatever framework you know, the initial stage of the interview is always based on the programming sense, coding skills, and problem-solving capabilities. To test these, all the interviewers start interview from core programming problems and most of these programming problems are from core java concepts. Here, in this article, I have tried to put some initial level of Java programming questions to get through an interview process. These programs are helpful to both freshers and experienced Java professionals.

Keep an eye on this page as I will be regularly adding and updating more and more interview questions.

Write a Java program to find the largest sum of the contiguous subarray in a given Array

Write a Java program to find the largest sum of the contiguous subarray in a given Array. The given array might contain negative elements too and hence we need to find out a contiguous sub-array whose sum would be maximum....

Write a Java program to rotate a matrix

Given a 2D matrix of N X N. Write a Java program to rotate the matrix in a clockwise direction by 90 degrees. The 0th row of the given matrix will be transformed to the nth column, the 1st row will be transformed to the n-1 column, and so on. Below is its representation....

Writing a Java program to rotate an array by d elements.

For any given array of length n, rotating it by elements d means moving its first d elements either at the end of the array or moving the last d elements to the beginning of the array....

Java Program to Find Union and Intersection of Arrays in Java

Writing a Java program to find first non-repeated character in a String is a common programming interview question to test the usage of Set interface provided in Java collection framework....

Java Program to Find First non Repeated Character in a String

Writing a Java program to find first non-repeated character in a String is a common programming interview question. For example, the first non-repeated character in the String 'devglan for developers' is 'g'....

Write a Java Program to Find missing Number in an Array

Write a java program to find a missing number in an Array of length N-1 containing elements from 1 to N. The trick to find the missing number is using the mathematical formula of Sum of Series....

Write a Java Program to Compare Files in Java

When you are learning Java, network programming can be a great source of practicing Java. In this program, we will see how we can compare two different files in Java. Comparing files in java also can help you to differentiate between the local and the remote files. You can quickly identify the duplicate lines, which allows you to remove the file entirely. First, we will be comparing the files using BufferedReader but this way of comparing files is not memory efficient and requires more execution time. Hence, we will be using a highly advanced technique called memory mapping using RandomAccessFile from java.io package....

Write a Java Program to Print 1 To 10 Without Using Loop

Write a java program to print 1 to 10 without using any loop.This can be achieved by using recursion in Java.Following is the sample code....

Write a Java Program to Reverse an Array in Place Without Using Any Second Array

Write a java program to reverse an array in place without using any second array.Here, we can loop till the middle index of the array and swap the first element with last element, swap the second element with second last element until we reach the middle of the array....

Write a Java Program to Find the Longest Palindrome Present in a Given String

A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward, such as madam. Write a java program to find the longest palindrome present in a given string. For example, in the string abcba , the longest palindrome is abcba and similarly in abcmadamcbamadam , the longest palindrome is abcmadamcba ....

Write a Java Program to Find the Second Largest Number in an Array

Write a java program to find the second largest number in an array.There are multiple ways to achieve this. We can sort any given array in a descending order and pick the second index element.The main concept here is to sort the given array.This can be achieved via Arrays.sort() or Collection.sort() and once the given array is sorted the second largest number can be easily found....

Write a Java Program to Remove Common Characters From Given Strings

In many java interviews, it is asked this question to compare two strings and remove the common character from the given strings to check the programming aptitude.For example, suppose there are two string, s1 = "abcfgh" and s2 = "aasdf" and after removal of common character the value of s1 and s2 becomes bcgh and sd respectivly. Following is the java program to remove the common characters from any given strings....

Java Program To Check If A Given Number is A Perfect Number

A perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself.Write a java program to check if a given number is a perfect number or not....

Check Given String is Rotation of Another String

Given two string s1 and s2 then write a java program to check if s1 is the rotation of another string s2.Here rotation means, each character of s2 must be the same character of s1 but only thing is that the character in s2 can be present at any random position. Following is the java program to check if a given string is a rotation of another string....

Java Program to Find LCM of a Two Given Number

Write a Java program to find LCM of a given two numbers.LCM stands for Lowest Common Multiple. LCM of a two given number a and b is the smallest positive integer that is divisible by both a and b.For example the LCM of 4 and 6 is 12. Following is the java program to find LCM using while and for loop....

Write a Java Program to Test Given Words are Anagram or Not

Two words are said to be anagrams, if both the words contain same set of characters with all original letters exactly once. For example, the word program can be re-arranged as grampor and these both words form an anagram. Following is a java program to check if a string is anagram or not. There are two ways for this test - One is using equals() method provided in Arrays class and another by comparing each character of he words....

Write a Java Program to Add Two 2D Matrix

A matrix is a rectangular array of numbers or expressions arranged in rows and columns.Below is the java program to add two 2D matrices.We can change the dimension variables accordingly for 3D and 4D matrix....

Write a Java Program to Perform Binary Search in a Sorted Array

Binary search is one of the famous and fundamental algorithm in computer science which solves a large number of problems in developing applications and APIs. It uses divide and conquer approach to find out the element.Here, we will be writing a sample program in java that implements binary search.The given array is a sorted array of n elements and we have to search the position a given element inside the array....

Write a Java Program to find Factorial of a Given Number

Write a program to find factorial of a given number is a common java program asked in any interview to freshers.The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example factorial of 4 is 4*3*2 = 24.There are 2 ways to find a factorial of a given number - One by using for loop and the other using recursion.Following java program uses for loop to find factorial of a given number....

Java Program to Reverse a Given String without using Predefined Functions

Write a java program to reverse a given string using recursion without using any predefined function.This program checks the understanding of recursion in programming language and also checks the programming sense.Here, the method reverseString() is called recursively to revrse a given string.Following is the complete program....

Java program to Find Permutations of a Given String

Write a java program to find all the permutations of any given string.Permutation is the each of several possible ways in which a set or number of things can be ordered or arranged.Order matters in case of Permutation.For example, the permutation of ab will be ab and ba.Following is the java program to find permutation of a given string....

Java program to reverse a given number

Write a java program to reverse a given number by using only numeric operators.Suppose, if you are given an input of 4567 then the output should be 7654.In the program below, we have only used the modulus or remainder and / operator.Following is the complete program....

Java program to find sum of prime numbers which are less than a given number

Write a java program to find the sum of all the prime numbers less than a given natural number N. The main purpose of this interview question is to check the programming sense and capabilities to check how good you are to convert existing logic into code. The question is mostly asked to freshers.The only main logic in this program is to find the prime numbers.Prime number is a number that is greater than 1 and divided by 1 or itself.For reminder, 2 is also a prime number....

Java program to find max repeated words from a file

In java interview, this program can be asked in a multiple ways such as write program to find max repeated words or duplicate words or the count of each duplicate words.Whatever the question, the main programming concept is the same to count the occurrence of each word in a .txt file. To solve this programmatically, we can use Map implementation in Java that does not allow any duplicate key and at the end of iteration we can find out the count.Following is the complete program.Here, we are using java 8 Lambda operator during sorting....

Java Program to find max two numbers in an array

In many java interviews especially for freshers, it is asked to write program to find max two numbers from a given array.This kind of program is good to check the programming sense as this program does not use any inbuilt java sorting functions or predefined data structures or collections.It simply uses java iterations and programming sense to swap in between the numbers and find the solution.Following is the implementation....

Java Program to Find line with max character length in Descending Order

This java interview program is about finding lines with max character from a file in descending order.In this case, we will be using buffered reader to read a file and use java provided data structure TreeSet to hold the line and it's character length as it automatically maintains ascending order.Following is the program to find two lines with max characters in descending order....

Java Program to Find middle index of array where both ends sum is equal

In the java interview, you will be asked to find the middle index or position of a given array where sum of numbers preceding the index is equals to sum of numbers succeeding the index.There are two ways to solve this problem.One is to use 2 for loops - one starting from the last index to the middle index and another starting from start index to middle index. Another way to solve it by using while loop - the while loop should stop when the start index crosses the end index. Following is the program to achieve this using while loop....

Java Program to Find Duplicate Character from a String and Count of repetition

While dealing with string, many of the time it is required to find or remove duplicate character from a string.Following is the java program to find duplicate or repeated characters from a given string.The program also results the count of the duplicate characters....

Java Program to Find Distinct Word List From a File

Java program to find distinct words from file is a very common question in java interview.In the following program, we will be using BufferedReader to read a file and then retain distinct words from it. To achieve this, we will be using Set to store all the words from a file and since, set dos not allow duplicates, we can easily find the distinct words.Following is the complete java program for this....

Java Program to test if a given number is Fibonacci or not

Fibonacci numbers are the numbers in which each number is the sum of the two preceding numbers.For example 1, 1, 2, 3, 5, 8, 13, 21, 34, ...The first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence.In most of the java interview, itapos;s a common programming question to check a given number is fibonacci number or not....

Java Program to test if a given number is Armstrong Number or not

Armstrong Number is a number that is the sum of its own digits each raised to the power of the number of digits.For example 371 is an Armstrong number as 3^3+7^3+1^3 = 371. It is also sometimes called as narcissistic number or pluperfect digital invariant (PPDI). Following is the java program to test if a given number is an armstrong number or not....

15 Common Problem-Solving Interview Questions

HackerRank AI Promotion

In an interview for a big tech company, I was asked if I’d ever resolved a fight — and the exact way I went about handling it. I felt blindsided, and I stammered my way through an excuse of an answer.

It’s a familiar scenario to fellow technical job seekers — and one that risks leaving a sour taste in our mouths. As candidate experience becomes an increasingly critical component of the hiring process, recruiters need to ensure the problem-solving interview questions they prepare don’t dissuade talent in the first place. 

Interview questions designed to gauge a candidate’s problem-solving skills are more often than not challenging and vague. Assessing a multifaceted skill like problem solving is tricky — a good problem solver owns the full solution and result, researches well, solves creatively and takes action proactively. 

It’s hard to establish an effective way to measure such a skill. But it’s not impossible.

We recommend taking an informed and prepared approach to testing candidates’ problem-solving skills . With that in mind, here’s a list of a few common problem-solving interview questions, the science behind them — and how you can go about administering your own problem-solving questions with the unique challenges of your organization in mind.

Key Takeaways for Effective Problem-Solving Interview Questions

  • Problem solving lies at the heart of programming. 
  • Testing a candidate’s problem-solving skills goes beyond the IDE. Problem-solving interview questions should test both technical skills and soft skills.
  • STAR, SOAR and PREP are methods a candidate can use to answer some non-technical problem-solving interview questions.
  • Generic problem-solving interview questions go a long way in gauging a candidate’s fit. But you can go one step further by customizing them according to your company’s service, product, vision, and culture. 

Technical Problem-Solving Interview Question Examples

Evaluating a candidates’ problem-solving skills while using coding challenges might seem intimidating. The secret is that coding challenges test many things at the same time — like the candidate’s knowledge of data structures and algorithms, clean code practices, and proficiency in specific programming languages, to name a few examples.

Problem solving itself might at first seem like it’s taking a back seat. But technical problem solving lies at the heart of programming, and most coding questions are designed to test a candidate’s problem-solving abilities.

Here are a few examples of technical problem-solving questions:

1. Mini-Max Sum  

This well-known challenge, which asks the interviewee to find the maximum and minimum sum among an array of given numbers, is based on a basic but important programming concept called sorting, as well as integer overflow. It tests the candidate’s observational skills, and the answer should elicit a logical, ad-hoc solution.

2. Organizing Containers of Balls  

This problem tests the candidate’s knowledge of a variety of programming concepts, like 2D arrays, sorting and iteration. Organizing colored balls in containers based on various conditions is a common question asked in competitive examinations and job interviews, because it’s an effective way to test multiple facets of a candidate’s problem-solving skills.

3. Build a Palindrome

This is a tough problem to crack, and the candidate’s knowledge of concepts like strings and dynamic programming plays a significant role in solving this challenge. This problem-solving example tests the candidate’s ability to think on their feet as well as their ability to write clean, optimized code.

4. Subarray Division

Based on a technique used for searching pairs in a sorted array ( called the “two pointers” technique ), this problem can be solved in just a few lines and judges the candidate’s ability to optimize (as well as basic mathematical skills).

5. The Grid Search 

This is a problem of moderate difficulty and tests the candidate’s knowledge of strings and searching algorithms, the latter of which is regularly tested in developer interviews across all levels.

Common Non-Technical Problem-Solving Interview Questions 

Testing a candidate’s problem-solving skills goes beyond the IDE . Everyday situations can help illustrate competency, so here are a few questions that focus on past experiences and hypothetical situations to help interviewers gauge problem-solving skills.

1. Given the problem of selecting a new tool to invest in, where and how would you begin this task? 

Key Insight : This question offers insight into the candidate’s research skills. Ideally, they would begin by identifying the problem, interviewing stakeholders, gathering insights from the team, and researching what tools exist to best solve for the team’s challenges and goals. 

2. Have you ever recognized a potential problem and addressed it before it occurred? 

Key Insight: Prevention is often better than cure. The ability to recognize a problem before it occurs takes intuition and an understanding of business needs. 

3. A teammate on a time-sensitive project confesses that he’s made a mistake, and it’s putting your team at risk of missing key deadlines. How would you respond?

Key Insight: Sometimes, all the preparation in the world still won’t stop a mishap. Thinking on your feet and managing stress are skills that this question attempts to unearth. Like any other skill, they can be cultivated through practice.

4. Tell me about a time you used a unique problem-solving approach. 

Key Insight: Creativity can manifest in many ways, including original or novel ways to tackle a problem. Methods like the 10X approach and reverse brainstorming are a couple of unique approaches to problem solving. 

5. Have you ever broken rules for the “greater good?” If yes, can you walk me through the situation?

Key Insight: “Ask for forgiveness, not for permission.” It’s unconventional, but in some situations, it may be the mindset needed to drive a solution to a problem.

6. Tell me about a weakness you overcame at work, and the approach you took. 

Key Insight: According to Compass Partnership , “self-awareness allows us to understand how and why we respond in certain situations, giving us the opportunity to take charge of these responses.” It’s easy to get overwhelmed when faced with a problem. Candidates showing high levels of self-awareness are positioned to handle it well.

7. Have you ever owned up to a mistake at work? Can you tell me about it?

Key Insight: Everybody makes mistakes. But owning up to them can be tough, especially at a workplace. Not only does it take courage, but it also requires honesty and a willingness to improve, all signs of 1) a reliable employee and 2) an effective problem solver.

8. How would you approach working with an upset customer?

Key Insight: With the rise of empathy-driven development and more companies choosing to bridge the gap between users and engineers, today’s tech teams speak directly with customers more frequently than ever before. This question brings to light the candidate’s interpersonal skills in a client-facing environment.

9. Have you ever had to solve a problem on your own, but needed to ask for additional help? How did you go about it? 

Key Insight: Knowing when you need assistance to complete a task or address a situation is an important quality to have while problem solving. This questions helps the interviewer get a sense of the candidate’s ability to navigate those waters. 

10. Let’s say you disagree with your colleague on how to move forward with a project. How would you go about resolving the disagreement?

Key Insight: Conflict resolution is an extremely handy skill for any employee to have; an ideal answer to this question might contain a brief explanation of the conflict or situation, the role played by the candidate and the steps taken by them to arrive at a positive resolution or outcome. 

Strategies for Answering Problem-Solving Questions

If you’re a job seeker, chances are you’ll encounter this style of question in your various interview experiences. While problem-solving interview questions may appear simple, they can be easy to fumble — leaving the interviewer without a clear solution or outcome. 

It’s important to approach such questions in a structured manner. Here are a few tried-and-true methods to employ in your next problem-solving interview.

1. Shine in Interviews With the STAR Method

S ituation, T ask, A ction, and R esult is a great method that can be employed to answer a problem-solving or behavioral interview question. Here’s a breakdown of these steps:

  • Situation : A good way to address almost any interview question is to lay out and define the situation and circumstances. 
  • Task : Define the problem or goal that needs to be addressed. Coding questions are often multifaceted, so this step is particularly important when answering technical problem-solving questions.
  • Action : How did you go about solving the problem? Try to be as specific as possible, and state your plan in steps if you can.
  • Result : Wrap it up by stating the outcome achieved. 

2. Rise above difficult questions using the SOAR method

A very similar approach to the STAR method, SOAR stands for S ituation, O bstacle, A ction, and R esults .

  • Situation: Explain the state of affairs. It’s important to steer clear of stating any personal opinions in this step; focus on the facts.
  • Obstacle: State the challenge or problem you faced.
  • Action: Detail carefully how you went about overcoming this obstacle.
  • Result: What was the end result? Apart from overcoming the obstacle, did you achieve anything else? What did you learn in the process? 

3. Do It the PREP Way

Traditionally used as a method to make effective presentations, the P oint, R eason, E xample, P oint method can also be used to answer problem-solving interview questions.  

  • Point : State the solution in plain terms. 
  • Reasons: Follow up the solution by detailing your case — and include any data or insights that support your solution. 
  • Example: In addition to objective data and insights, drive your answer home by contextualizing the solution in a real-world example.
  • Point : Reiterate the solution to make it come full circle.

How to Customize Problem-Solving Interview Questions 

Generic problem-solving interview questions go a long way in gauging a candidate’s skill level, but recruiters can go one step further by customizing these problem-solving questions according to their company’s service, product, vision, or culture. 

Here are some tips to do so:

  • Break down the job’s responsibilities into smaller tasks. Job descriptions may contain ambiguous responsibilities like “manage team projects effectively.” To formulate an effective problem-solving question, envision what this task might look like in a real-world context and develop a question around it.  
  • Tailor questions to the role at hand. Apart from making for an effective problem-solving question, it gives the candidate the impression you’re an informed technical recruiter. For example, an engineer will likely have attended many scrums. So, a good question to ask is: “Suppose you notice your scrums are turning unproductive. How would you go about addressing this?” 
  • Consider the tools and technologies the candidate will use on the job. For example, if Jira is the primary project management tool, a good problem-solving interview question might be: “Can you tell me about a time you simplified a complex workflow — and the tools you used to do so?”
  • If you don’t know where to start, your company’s core values can often provide direction. If one of the core values is “ownership,” for example, consider asking a question like: “Can you walk us through a project you owned from start to finish?” 
  • Sometimes, developing custom content can be difficult even with all these tips considered. Our platform has a vast selection of problem-solving examples that are designed to help recruiters ask the right questions to help nail their next technical interview.

Get started with HackerRank

Over 2,500 companies and 40% of developers worldwide use HackerRank to hire tech talent and sharpen their skills.

Recommended topics

  • Coding Questions
  • Interview Preparation

Abstract, futuristic image generated by AI

6 REST API Interview Questions Every Developer Should Know

Arc Talent Career Blog

50+ Important Java Interview Questions and Answers to Know

how to answer Java Interview Questions

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

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

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

Basic Java Interview Questions

Intermediate java interview questions.

  • Advanced Java Interview Questions

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

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

Try HireAI and hire top developers now →

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

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

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

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

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

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

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

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

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

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

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

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

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

Struggling with interview prep? Meet senior developers from Amazon, Microsoft, and Google now on Codementor. They’ll help you tackle coding challenges, practice interviews, and sharpen your skills in live 1:1 sessions. Book a session with our interview prep experts today! Your first 15 minutes are free.

Explore our other software development interview questions and answers to prep for your next remote job.

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

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

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

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

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

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

or, with Java 8:

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

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

will print  false .

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

8. What is the problem with this code:

There are, in fact, two problems:

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

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

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

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

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

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

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

9. What is the JIT?

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

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

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

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

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

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

The problem here is that this expression:

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

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

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

In this code:

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

It is an  IntConsumer .

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

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

12. What is the problem with this code?

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

This should be used instead:

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

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

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

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

The contents will be:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

16. Can an  enum  be extended?

No. Enum types are final by design.

17. How threadsafe is  enum  in Java?

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

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

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

Local variables are stored on the stack.

19. Identify the problem in the below Java code:

A classic example of escaping references.

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

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

20. When do you use volatile variables?

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

More Important Basic Questions for Java Developers

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

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

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

problem solving question in java

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

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

22. What is the difference between HashMap and ConcurrentHashMap ?

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

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

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

24. What is a Service?

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

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

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

26. What is the marker interface in Java?

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

27. How are Annotations better than Marker Interfaces?

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

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

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

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

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

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

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

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

Other Intermediate Interview Questions for Java Developers

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

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

You can also explore HireAI to skip the line and:

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

Advanced Java Interview Questions for Experienced Developers

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

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

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

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

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

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

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

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

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

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

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

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

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

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

37. What is the advantage of a generic collection?

They enable stronger type checks at compile time.

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

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

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

' src=

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

Further reading

how to answer Spring Interview Questions

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

software developer or software engineering questions to ask tech recruiters

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

how to answer Angular Interview Questions for AngularJS

29 Angular Interview Questions and Answers to Practice & Prepare For

questions to ask at an interview for software developers interview questions to ask

31 Questions to Ask at an Interview for Software Development Jobs

how to answer React Interview Questions for React.js

55+ Top React Interview Questions and Answers to Prepare For

best data analysis interview questions to practice for data analytics jobs

10 Data Analyst Interview Questions & Answers You Should Prepare For

Java : Switch Statement - Exercises and Solution

1. Write a program to read a weekday number and print weekday name using switch statement

2. Write a program to read gender(M/F) and print the corresponding gender using a switch statement

3. Write a program to Check whether a character is a vowel or consonant using switch statement

4. Write a program to Check whether the number is even or odd using switch statement

5. Write a program to Find the number of days in a month using a switch statement

6. Write a program to create simple calculator using switch Statement

7. Write a program to print remark according to the grade obtained using switch statement

8. Write a program to Menu driven program using switch statement ( Find addition, subtraction, multiplication and division of to integer numbers )

9. Write a program to check whether a person is eligible to vote or Not using switch statement

10. Write a program to find the Maximum of Two Numbers using switch statement

Basic Programs

  • Java Materials
  • Java Introduction
  • History of Java
  • Installation
  • Basic Program in Java
  • Command Line Arguments in Java
  • Single and Multi Line Comments in Java
  • Variables in Java
  • Type Casting in Java
  • Arithmetic Operators in Java
  • Arithmetic Assignment operators in Java
  • Relational Operators in Java
  • Logical Operators in Java
  • Conditional or Ternary Operators in Java
  • Unary Operators in Java
  • Bitwise & Shift Operators in Java
  • Scanner Class in Java
  • IF Statement in Java
  • IF ELSE Statement in Java
  • ELSE IF Ladder in Java
  • Nested If in Java
  • Switch Statement in Java
  • Group Switch Statement in Java
  • While Loop in Java
  • do While Loop in Java
  • For Loop in Java
  • Enhanced for loop in Java
  • Nested For Loop in Java
  • Break & Continue in Java
  • Factorial in Java
  • Sum and Average of N Numbers in Java
  • Fibonacci Series in Java
  • Reverse of n digit number in Java
  • Number is Palindrome or Not in Java
  • Armstrong Number in Java
  • Armstrong Number between 100-999 in Java
  • Multiplication tables in Java
  • Factor of the given number in Java
  • Number is prime or not in Java
  • Prime Number between 100-999 in Java
  • Perfect Number in Java
  • Strong Number in Java
  • Array in Java
  • Count odd or even numbers in Java
  • Ascending Order in Java
  • Insert an element (specific position) into an array in Java
  • Find the duplicate values of an array in Java
  • Two Dimension Arrays in Java
  • Jagged-Array in Java
  • Jagged-Array Using For Each Loop in Java
  • ASCII in Java
  • String in Java
  • StringBuffer & StringBuilder in Java
  • count Vowels,Capital letters,small letters,numbers and space in Java
  • Reverse A String in Java
  • convert the given string into UPPERCASE in Java
  • convert the given string into lowercase in Java
  • convert the given string into Capitalized Each Word in Java
  • convert the given string into tOGGLE cASE wORD in Java
  • Math Functions in Java
  • Types of Methods in Java
  • Returning Arrays from Method in Java
  • Static Member Function in Java
  • Convert Decimal To Binary in Java
  • Introduction of Object Oriented Programming in Java
  • Class & object in Java
  • Data Hiding Getter & Setter in Java
  • Constructor in Java
  • Parametrized Constructor & Constructor Overloading in Java
  • Copy Constructor in Java
  • Arrays of Objects in Java
  • Nesting of Methods in Java
  • Single Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Method With varargs in Java
  • Method Overloading in Java
  • Method Overriding in Java
  • Abstract Class in Java
  • Smart Phone Example using Abstract Class in Java
  • What is interface in Java
  • Implement multiple interfaces in Java
  • More About Interface in Java
  • Difference Between Abstract Class and Interface in Java
  • Nested Inner Class in Java
  • Local Inner Class in Java
  • Anonymous Inner Class in Java
  • Static Inner Class in Java
  • Static Members in Java
  • Static Blocks in Java
  • Final in Java
  • Final Methods in Java
  • Final Class in Java
  • Singleton Class in Java
  • Enumeration in Java
  • Date and Time Functions in Java
  • Wrapper Class - Converting primitive number to number object in Java
  • Wrapper Class - Converting number object to primitive number in Java
  • Wrapper Class - Converting primitive number to string object in Java
  • Wrapper Class - Converting string object to primitive numbers in Java
  • Wrapper Class - Converting numeric string object to primitive numbers in Java
  • Shallow Copy Object Cloning in Java
  • Deep Copy Object Cloning in Java
  • Java Reflection API in Java
  • Calling Private Method in Java Class using Reflection API in Java

Abstract Window Toolkit

  • Java AWT (Abstract Window Toolkit)
  • Frame in Java AWT
  • Button and ActionListener in Java AWT
  • CheckBox in Java AWT
  • RadioButton in Java AWT
  • TextField in Java AWT
  • Basic Addition Program in Java AWT
  • TextArea in Java AWT
  • Count Words and Characters in Java AWT
  • Choice in Java AWT
  • List in Java AWT
  • Canvas in Java AWT
  • MenuBar,Menu,MenuItem in Java AWT
  • Panel in Java AWT
  • Form Design Using Java AWT
  • Database Operation in Java AWT

SQLITE CRUD

  • SQLite in Java
  • MySQL in Java
  • Swing in Java
  • JavaFX in Java

Java Programs

  • Patterns in Java

Exercise Questions and Answers

  • Basic Exercise Programs in Java
  • Conversion Programs in Java
  • IF Statement Exercise in Java
  • Looping Statement Exercise in Java
  • Array Exercise in Java
  • DateTime Exercise in Java
  • String Exercise in Java
  • Math Exercise in Java
  • Switch Exercise in Java
  • EnumSet Collection Exercise in Java
  • Recursion Function Exercise in Java
  • FileHandling Exercise in Java
  • Class and Object Exercise in Java
  • Thread Exercise in Java
  • Inheritance Exercise in Java
  • Lambda Expression Exercise in Java
  • Method Overriding Exercise in Java
  • Method Overloading Exercise in Java
  • Abstract Class Exercise in Java
  • Interface Exercise in Java
  • Method with Varargs Exercise in Java
  • Constructor Exercise in Java

Java Collection Programs

  • ArrayList Exercise in Java
  • LinkedList Exercise in Java
  • TreeSet Exercise in Java
  • TreeMap Exercise in Java
  • HashMap Exercise in Java
  • HashSet Exercise in Java
  • Vector Class Exercise in Java
  • Stack Exercise in Java
  • Queue Exercise in Java
  • Basic Example in Java
  • Mathematical Operations in Java
  • More than one Class in Java
  • Command Line Argument
  • Sum of Values in Java
  • Arithmetic Operation in Java
  • Relational Operator in Java
  • Logical Operator in Java
  • Increment & Decrement in Java
  • Conditional Operators in Java
  • Decision Control in Java
  • Else-If Statement in Java
  • Student Mark List using Nested If
  • Switch Case Example in Java
  • While Loop Example in Java
  • Do While Loop Example in Java
  • For Loop Example in Java
  • Nested For Loop Example in Java
  • Enhanced For Loop Example in Java
  • Jump Lable using For Loop in Java
  • Classes and Object in Java
  • Constructor Example in Java
  • Function Overloading Example in Java
  • Static Function Example in Java
  • Nested Member Function in Java
  • Single Inheritance Example in Java
  • Super Class Example in Java
  • Method Overriding Example in Java
  • Methods with Varargs in Java
  • Arrays Example in Java
  • Two Dimensional Array in Java
  • String Function Example in Java
  • String Buffer Class Example in Java
  • Vector Class Example in Java
  • Wrapper Class Example in Java
  • AutoBoxing and Un boxing in Java
  • Enumeration Example in Java
  • Multiple Interface in Java
  • Simple Package Example in Java
  • Basic Thread Example in Java
  • Thread Method Example in Java
  • Arithmetic Exception in Java
  • Array Index Out Of Bounds Exception Example

Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions

Download Interview guide PDF

Java collections interview questions, download pdf, what is collection in java.

In Java , a collection is a framework that provides an architecture for storing and manipulating a collection of objects. In JDK 1.2, a new framework called "Collection Framework" was created, which contains all of the collection classes and interfaces. 

Collections in Java are capable of doing any data operations such as searching, sorting, insertion, manipulation, and deletion.

A single unit of objects in Java is referred to as a collection. The two basic “root” interfaces of Java collection classes are the Collection interface (java.util.Collection) and the Map interface(java.util.Map). Many interfaces (Set, List, Queue, Deque) and classes are available in the Java Collection framework (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

problem solving question in java

Need for the Collection framework:-

Prior to the introduction of Collection Framework (or JDK 1.2), the standard techniques for aggregating Java objects (or collections) were Arrays, Vectors, or Hash Tables. There was no common interface for all of these collections. As a result, while the basic goal of all the collections is the same, their implementation was specified independently and there was no correlation between them. Furthermore, users find it challenging to remember all of the various methods, syntax, and constructors included in each collection class.

Java Collections Interview Questions for Freshers

1. differentiate between hashset and treeset. when would you prefer treeset to hashset.

Following are the differences between HashSet and TreeSet:-

  • HashSet: For search, insert, and remove operations, it takes constant time on average. TreeSet is slower than HashSet. A hash table is used to implement HashSet.
  • TreeSet: For search, insert, and delete, TreeSet takes O(Log n), which is higher than HashSet. TreeSet, on the other hand, preserves ordered data. Higher() (Returns the least higher element), floor(), ceiling(), and other operations are also supported. In TreeSet, these operations are likewise O(Log n), and HashSet does not implement them. A Self-Balancing Binary Search Tree is used to implement TreeSet (Red Black Tree). In Java, TreeSet is backed by TreeMap.
  • Way of storing elements   The elements of a HashSet are not ordered. In Java, the TreeSet class keeps objects in a Sorted order defined by the Comparable or Comparator methods. By default, TreeSet components are sorted in ascending order. It has a number of methods for dealing with ordered sets, including first(), last(), headSet(), tailSet(), and so on.
  • Allowing Null values  Null objects are allowed in HashSet. TreeSet does not allow null objects and throws a NullPointerException. This is because TreeSet compares keys using the compareTo() method, which throws java.lang. NullPointerException.
  • Comparison HashSet compares two objects in a Set and detects duplicates using the equals() method. For the same purpose, TreeSet employs the compareTo() method. If equals() and compareTo() are not consistent, that is, if equals() returns true for two equal objects but compareTo() returns zero, the contract of the Set interface will be broken, allowing duplicates in Set implementations like TreeSet.

Following are the cases when TreeSet is preferred to HashSet :

  • Instead of unique elements, sorted unique elements are required. TreeSet returns a sorted list that is always in ascending order.
  • The locality of TreeSet is higher than that of HashSet. If two entries are close in order, TreeSet places them in the same data structure and hence in memory, but HashSet scatters the entries over memory regardless of the keys to which they are linked.
  • To sort the components, TreeSet employs the Red-Black tree method. TreeSet is a fantastic solution if you need to do read/write operations regularly.

2. Differentiate between Collection and collections in the context of Java.

Collection : In the java.util.package, there is an interface called a collection. It's used to represent a collection of separate objects as a single entity. It's equivalent to the container in the C++ programming language. The collection framework's root interface is referred to as the collection. It has a number of classes and interfaces for representing a collection of individual objects as a single unit. The key sub-interfaces of the collection interface are List, Set, and Queue. Although the map interface is part of the Java collection framework, it does not inherit the interface's collection. The Collection interface's most significant functions are add(), remove(), clear(), size(), and contains().

Collections : The java.util.package has a utility class called Collections. It defines various utility methods for working with collections, such as sorting and searching. All of the methods are static. These techniques give developers much-needed convenience, allowing them to interact with Collection Framework more successfully. It provides methods like sort() to sort the collection elements in the normal sorting order, and min() and max() to get the minimum and maximum value in the collection elements, respectively.

problem solving question in java

Collection Collections
It's used to represent a collection of separate objects as a single entity. It defines a number of useful methods for working with collections.
It is an interface. It is a utility class.
Since Java 8, the Collection is an interface with a static function. Abstract and default methods can also be found in the Interface. It only has static methods in it.

3. Explain the hierarchy of the Collection framework in Java.

The entire collection framework hierarchy is made up of four fundamental interfaces: Collection, List, Set, Map, and two specific interfaces for sorting called SortedSet and SortedMap. The java.util package contains all of the collection framework's interfaces and classes. The following diagram depicts the Java collection structure.

problem solving question in java

Here, e denotes extends, i denotes implements

  • Extends : The keyword extends is used to create inheritance between two classes and two interfaces.
  • Implements : The keyword implements are used to create inheritance across classes and interfaces.

4. What are the advantages of the Collection framework?

Following are the advantages of the Collection framework:-

Consistent API : The API has a core set of interfaces like Collection, Set, List, or Map, and all the classes (ArrayList, LinkedList, Vector, and so on) that implement these interfaces have some common set of methods.

Cuts programming effort : Instead of worrying about the Collection's design, a programmer may concentrate on how best to use it in his program. As a result, the fundamental principle of Object-oriented programming (i.e. abstraction) has been applied successfully.

Improves program speed and quality by offering high-performance implementations of useful data structures and algorithms, as the programmer does not have to worry about the optimum implementation of a certain data structure in this scenario. They can simply use the best implementation to improve the performance of their program significantly.

problem solving question in java

5. Explain the various interfaces used in the Collection framework.

The collection framework has several interfaces, each of which is used to store a different sort of data. The interfaces included in the framework are listed below.

1. Iterable Interface : This is the collection framework's primary interface. The iterable interface is extended by the collection interface. As a result, all interfaces and classes implement this interface by default. This interface's main purpose is to provide an iterator for the collections. As a result, this interface only has one abstract method, the iterator. 

2. Collection Interface : The collection framework's classes implement this interface, which extends the iterable interface. This interface covers all of the basic methods that every collection has, such as adding data to the collection, removing data from the collection, clearing data, and so on. All of these methods are incorporated in this interface because they are used by all classes, regardless of their implementation style. Furthermore, including these methods in this interface guarantees that the method names are consistent across all collections. In summary, we may conclude that this interface lays the groundwork for the implementation of collection classes.

3. List Interface : The collection interface has a child interface called the list interface. This interface is devoted to list data, in which we can store all of the objects in an ordered collection. This also allows for the presence of redundant data. Various classes, such as ArrayList, Vector, Stack, and others, implement this list interface. We can create a list object with any of these classes because they all implement the list.

4. Queue Interface : A queue interface, as the name implies, follows the FIFO (First In First Out) order of a real-world queue line. This interface is for storing all elements in which the order of the elements is important. When we try to shop at a store, for example, the bills are issued on a first-come, first-served basis. As a result, the individual whose request is first in line receives the bill first. PriorityQueue, Deque, ArrayDeque, and other classes are available. Because all of these subclasses implement the queue, we can use any of them to create a queue object.

5. Deque Interface : It differs slightly from the queue data structure.  Deque, also known as a double-ended queue, is a data structure in which elements can be added and removed from both ends. The queue interface is extended by this interface. ArrayDeque is the class that implements this interface. Because this class implements the deque, we can use it to create a deque object.

6. Set Interface : A set is an unordered group of objects in which duplicate values cannot be kept. This collection is utilised when we want to avoid duplication of things and only keep the ones that are unique. Various classes, such as HashSet, TreeSet, LinkedHashSet, and others, implement this set interface. We can create a set object with any of these classes because they all implement the set.

7. Sorted Set Interface : This interface resembles the set interface in appearance. The only difference is that this interface provides additional methods for maintaining element ordering. The sorted set interface is an extension of the set interface that is used to manage sorted data. TreeSet is the class that implements this interface. We can create a SortedSet object using this class because it implements the SortedSet interface.

  • Software Dev
  • Data Science

6. Difference between ArrayList and LinkedList.

problem solving question in java

ArrayList LinkedList
The elements of this class are stored in a dynamic array. This class now supports the storage of all types of objects thanks to the addition of generics. The elements of this class are stored in a doubly-linked list. This class, like the ArrayList, allows for the storage of any type of object.
The List interface is implemented by this class. As a result, this serves as a list. The List and Deque interfaces are both implemented by this class. As a result, it can be used as both a list and a deque.
Because of the internal implementation, manipulating an ArrayList takes longer. Internally, the array is scanned and the memory bits are shifted whenever we remove an element. Because there is no concept of changing memory bits in a doubly-linked list, manipulating it takes less time than manipulating an ArrayList. The reference link is changed after traversing the list.
This class is more useful when the application requires data storage and access. This class is more useful when the application requires data manipulation.

7. Differentiate between ArrayList and Vector in java.

Following are the differences between ArrayList and Vector in java :

  • Vector is synchronized, which means that only one thread can access the code at a time, however, ArrayList is not synchronized, which means that multiple threads can operate on ArrayList at the same time. In a multithreading system, for example, if one thread is executing an add operation, another thread can be performing a removal action.  If multiple threads access ArrayList at the same time, we must either synchronize the code that updates the list fundamentally or enable simple element alterations. The addition or deletion of element(s) from the list is referred to as structural change. It is not a structural change to change the value of an existing element.

problem solving question in java

  • Data Growth : Both ArrayList and Vector dynamically expand and shrink to make the most use of storage space, but the manner they do it is different. If the number of elements in an array exceeds its limit, ArrayList increments 50% of the current array size, while vector increments 100%, thereby doubling the current array size.
  • Performance : ArrayList is faster than vector operations because it is non-synchronized, but vector operations are slower since they are synchronized (thread-safe). When one thread works on a vector, it acquires a lock on it, requiring any other threads working on it to wait until the lock is released.
  • Vector can traverse over its elements using both Enumeration and Iterator, whereas ArrayList can only traverse using Iterator.

8. Differentiate between List and Set in Java.

The List interface is used to keep track of an ordered collection. It is the Collection's child interface. It is an ordered collection of objects that allows for the storage of duplicate values. The insertion order is preserved in a list, which enables positional access and element insertion. 

The set interface is part of java.util package and extends the Collection interface. It is an unordered collection of objects in which duplicate values cannot be stored. It's an interface for using the mathematical set. This interface inherits the Collection interface's methods and adds a feature that prevents duplicate elements from being inserted.

Set List
It is an unordered sequence. It is an ordered sequence.
Duplicate elements are not permitted in Set. Duplicate elements are allowed in the list
Access to items from a certain position is not permitted. Elements can be accessed based on their position.
A null element can only be stored once. It is possible to store several null elements.

9. Differentiate between Iterator and ListIterator in Java.

In Java's Collection framework, iterators are used to obtain elements one by one. It can be used on any type of Collection object. We can execute both read and remove operations using Iterator. Iterator must be used whenever we want to iterate elements in all Collection framework implemented interfaces, such as Set, List, Queue, and Deque, as well as all Map interface implemented classes. The only cursor accessible for the entire collection framework is the iterator.

ListIterator is only useful for classes that implement List collections, such as array lists and linked lists. It can iterate in both directions. When we wish to enumerate List elements, we must use ListIterator. This cursor has additional methods and capabilities than the iterator.

problem solving question in java

Iterator ListIterator
Only has the ability to traverse components in a Collection in a forward direction. In both forward and backward orientations, can traverse components in a Collection.
Iterators cannot be used to obtain indexes. It offers methods to get element indexes at any time while traversing List, such as next Index() and previous Index().
It aids in the traversal of Maps, Lists, and Sets. Only List may be traversed, not the other two.
It throws a Concurrent Modification Exception since it can't add elements. At any time, you can quickly add elements to a collection.
next(), remove(), and has Next are some of the Iterator's functions (). next(), previous(), has Next(), has Previous(), and add() are some of the List Iterator's methods

10. What is the difference between Array and Collection in java?

Array and Collection are equivalent in terms of storing object references and manipulating data, but they differ in a number of ways. The following are the primary distinctions between an array and a Collection:

Array Collection
Arrays have a set size, which means that once we build one, we can't change it to meet our needs. Collection are naturally grow-able and can be customized to meet our needs. We can change its size as per our requirement.
When it comes to performance, Arrays are the preferred to Collection. Considering performance, Collection are not preferred to Arrays.
Only homogeneous data type elements can be stored in arrays. Both homogeneous and heterogeneous components can be stored in a collection.
Because arrays have no underlying data structure, there is no ready-made method support. Any collection class is built on a standard data structure, and so there is ready-made method support for every demand as a performance. These methods can be used directly, and we are not responsible for their implementation.
Objects and primitives can both be stored in arrays. Only object types can be stored in a collection.
When it comes to memory, Arrays are not preferred to Collection. Considering memory, Collection are preferred to Arrays.

11. Can you add a null element into a TreeSet or HashSet?

We can add null elements in a HashSet but we cannot add null elements in a TreeSet. The reason is that TreeSet uses the compareTo() method for comparing and it throws a NullPointerException when it encounters a null element.

12. What is a priority queue in Java?

When the objects are meant to be processed in order of priority, a PriorityQueue is used. A Queue is known to follow the First-In-First-Out method, however, there are occasions when the components of the queue must be handled in order of priority, which is where the PriorityQueue comes into play. The priority heap is the foundation of the PriorityQueue. The members of the priority queue are ordered according to natural ordering or by a Comparator provided at queue construction time.

Serializable, Iterable<E>, Collection<E>, Queue<E> interfaces are implemented by the PriorityQueue class in Java.

problem solving question in java

13. What are some of the best practices while using Java Collections?

Following are some of the best practices while using Java Collections : 

  • Selecting the appropriate Collection: Before we use a collection, we must choose the most relevant collection for the problem we are seeking to solve. If we pick the wrong one, our program may still run, but it will be inefficient. On the other hand, if we pick the right one, our solution will be a lot simpler and our program will run much faster.
  • Specifying the initial capacity of the Collection : Almost all collection classes contain an overloaded constructor that determines the collection's initial capacity. That is, if we know exactly how many pieces will be added to the collection, we can define the initial capacity when establishing a new instance.
  • Using isEmpty() instead of size(): To check if a collection is empty or not we should use the isEmpty() method rather than finding the size of the collection and comparing it with zero. This enhances the readability of the code.
  • Using Iterators for iterating over the collections: We should use iterators for traversing over the collection elements instead of using a for loop for the same. The reason is that the iterator may throw ConcurrentModificationException if any other thread tries to modify the collection after the iterator has been created. This saves us from bugs.
  • Using Concurrent Collections over synchronized wrappers: Instead of utilizing the synchronized collections generated by the Collections.synchronizedXXX() methods, we should consider using concurrent collections from the java.util.concurrent package in multi-threaded applications. Because concurrent collections employ various synchronization strategies such as copy-on-write, compare-and-swap, and specific locks, they are designed to give maximum performance in concurrent applications.
  • Eliminating Unchecked warnings: We should not disregard unchecked warnings from the Java compiler. The ideal practice is to get rid of any warnings that aren't checked.
  • Favoring Generic types: We should build new methods with generic parameters in mind, and convert existing methods to use type parameters, just as we should with generic types because generic methods are safer and easier to use than non-generic ones. Generic methods also aid in the creation of APIs that are both general and reusable.

14. Differentiate between Set and Map in Java.

The Set interface is provided by the Java.util package. The set interface is established by extending the collection interface. We can't add the same element to it since it won't let us. Because it contains elements in a sorted order, it does not keep the insertion order. The Set interface in Java is used to build the mathematical Set.

Map is similar to Set in that it is used to store a collection of objects as a single entity. A key-value pair is used to store each object. Because each value is associated with a unique key, we can quickly obtain the value using just the key.

Set Map
It cannot have values that are repeated. It is not possible to add the same elements to a set. Only the unique value is stored in each class that implements the Set interface. It is possible for different keys to have the same value. The map has a unique key and values that are repeated. 
Using the keyset() and entryset() methods, we can quickly iterate the Set items. It is not possible to iterate across map elements. To iterate the elements, we must convert Map to Set.
The Set interface does not keep track of insertion order. Some of its classes, such as LinkedHashSet, however, keep the insertion order.  The Map does not keep track of the insertion sequence. Some Map classes, such as TreeMap and LinkedHashMap, do the same thing.

15. Differentiate between HashSet and HashMap.

HashSet is a Set Interface implementation that does not allow duplicate values. The essential point is that objects stored in HashSet must override equals() and hashCode() methods to ensure that no duplicate values are stored in our set.

HashMap is a Map Interface implementation that maps a key to a value. In a map, duplicate keys are not permitted.

problem solving question in java

HashSet HashMap
It implements the Set Interface. It implements the Map Interface.
It does not allow duplicate values. The key needs to be unique while two different keys can have the same value.
While adding an element it requires only one object as a parameter. While adding an entry, it requires two object values, the and the as the parameter.
Internally, HashSet uses HashMap to add entries. The key K in a HashSet is the argument supplied in the add(Object) method. For each value supplied in the add(Object) method, Java assigns a dummy value. There is no concept of duplicate values.
It is slower than HashMap. It is faster than HashSet.
It uses the add() method for adding elements. It uses the put() method for adding data elements.

16. What is the default size of the load factor in hashing based collection?

The default load factor size is 0.75 . The default capacity is calculated by multiplying the initial capacity by the load factor.

17. Differentiate between Array and ArrayList in Java.

Following are the differences between Arrays and ArrayLists in Java :

problem solving question in java

  • Java provides arrays as a fundamental functionality. ArrayList is a component of Java's collection system. As a result, It is used to access array members, while ArrayList provides a set of methods for accessing and modifying components.
  • ArrayList is not a fixed-size data structure, but Array is. When creating an ArrayList object, there is no need to provide its size. Even if we set a maximum capacity, we can add more parts afterward.
  • Arrays can include both primitive data types and class objects, depending on the array's definition. ArrayList, on the other hand, only accepts object entries and not primitive data types. Note that when we use arraylist.add(1);, the primitive int data type is converted to an Integer object.
  • Members of ArrayList are always referencing to objects at various memory locations since ArrayList can't be constructed for primitive data types  As a result, the actual objects in an ArrayList are never kept in the same place. The references to the real items are maintained in close proximity. Whether an array is primitive or an object depends on the type of the array. Actual values for primitive kinds are continuous regions, whereas allocation for objects is equivalent to ArrayList.
  • Many other operations, such as indexOf() and delete(), are supported by Java ArrayList. Arrays do not support these functions.

18. How can you make an ArrayList read-only in Java?

With the help of Collections.unmodifiableList() method, we can easily make an ArrayList read-only.  This function takes a changeable ArrayList as an input and returns the ArrayList's read-only, unmodified view.

We can see that as we try to add an element to a read-only ArrayList we get an exception thrown.

Java Collections Interview Questions for Experienced

1. why do we need synchronized arraylist when we have vectors (which are synchronized) in java.

Following are the reasons why we need synchronized ArrayLists even though we have Vectors :

  • Vector is slightly slower than ArrayList due to the fact that it is synchronized and thread-safe.
  • Vector's functionality is that it synchronizes each individual action. A programmer's preference is to synchronize an entire sequence of actions. Individual operations are less safe and take longer to synchronize.
  • Vectors are considered outdated in Java and have been unofficially deprecated. Vector also synchronizes on a per-operation basis, which is almost never done. Most java programmers prefer to use ArrayList since they will almost certainly synchronize the arrayList explicitly if they need to do so.

2. What do you understand about BlockingQueue in Java?

BlockingQueue is an interface that has been included along with a number of other concurrent Utility classes such as ConcurrentHashMap, Counting Semaphore, CopyOnWriteArrayList, and so on. In addition to queueing, the BlockingQueue interface enables flow control by adding blocking if either BlockingQueue is full or empty. 

A thread attempting to enqueue an element in a full queue will be blocked until another thread clears the queue, either by dequeuing one or more elements or by clearing the queue entirely. It also prevents a thread from deleting from an empty queue until another thread inserts an item. A null value is not accepted by BlockingQueue. Implementations of the Java BlockingQueue interface are thread-safe. BlockingQueue's methods are all atomic and use internal locks or other forms of concurrency management.

problem solving question in java

There are two types of BlockingQueue in Java. They are as follows :

Unbounded Queue : The blocked queue's capacity will be set to Integer. MAX VALUE. An unbounded blocking queue will never block since it has the potential to grow to a very big size. As you add more pieces, the size of the queue grows.

Bounded Queue : The bounded queue is the second type of queue. In the case of a bounded queue, the capacity of the queue can be passed to the constructor when the blocking queue is created.

3. Explain fail-fast and fail-safe iterators. Differentiate between them.

If the collection's structure is changed, Fail-Fast iterators immediately throw ConcurrentModificationException. While a thread is iterating over a collection, structural alteration includes adding or deleting any element. Fail-safe Iterator classes include ArrayList Iterator and HashMap Iterator. Fail-fast iterators use an internal indicator called modCount, which is updated each time a collection is modified, to determine if the collection has been structurally modified or not. When a fail-fast iterator gets the next item (through the next() method), it checks the modCount flag, and if it discovers that the modCount has been changed after the iterator was generated, it throws a ConcurrentModificationException.

If a collection is structurally updated while iterating over it, fail-safe iterators don't throw any exceptions. Because they operate on a clone of the collection rather than the original collection, they are referred to as fail-safe iterators. Fail-safe Iterators include the CopyOnWriteArrayList and ConcurrentHashMap classes.

problem solving question in java

Fail-Fast Fail-Safe
These types of iterators do not allow modifying the collection while iterating over it. These types of iterators allow modifying the collection while iterating over it.
It throws ConcurrentModificationException if the collection is modified while iterating over it. No exception is thrown if the collection is modified while iterating over it.
It uses the original collection while traversing the elements. It uses a copy of the original collection while traversing over it.
No extra memory is required in this case. Extra memory is required in this case.

4. What is the purpose of RandomAccess Interface? Name a collection type which implements this interface.

RandomAccess, like the Serializable and Cloneable interfaces, is a marker interface. There are no methods defined in any of these marker interfaces. Rather, they designate a class as having a specific capability. 

The RandomAccess interface indicates whether or not a given java.util.List implementation supports random access. This interface seeks to define a vague concept: what does it mean to be fast? A simple guide is provided in the documentation: The List has fast random access if repeated access using the List.get( ) method is faster than repeated access using the Iterator.next( ) method.

Repeated access using List.get( ):

Repeated access using Iterator.next( ):

5. Differentiate between Iterator and Enumeration.

Iterator : Because it can be applied to any Collection object, it is a universal iterator. We can execute both read and remove operations using Iterator. It's an enhanced version of Enumeration that adds the ability to remove an element from the list.

Enumeration : An enumeration (or enum) is a data type that is defined by the user. It's mostly used to give integral constants names, which make a program easier to comprehend and maintain. Enums are represented in Java (since 1.5) through the enum data type.

Iterator Enumeration
Iterator is a universal cursor since it works with all collection classes. Because it only applies to legacy classes, enumeration is not a universal cursor.
Iterators can make changes (for example, the delete() method removes an element from a Collection during traversal). The Enumeration interface is a read-only interface, which means you can't make any changes to the Collection while traversing its elements.
The remove() method is available in the Iterator class. The remove() method is not available in the enumeration.
Iterator is not a legacy interface. Iterator can traverse HashMaps, LinkedLists, ArrayLists, HashSets, TreeMaps, and TreeSets. Enumeration is a legacy interface for traversing Hashtables and Vectors.

6. What is the use of Properties class in Java? What is the advantage of the Properties file?

The key and value pair are both strings in the properties object. The java.util.Properties class is a Hashtable subclass.

It can be used to calculate the value of a property based on its key. The Properties class has methods for reading and writing data to and from the properties file. It can also be used to obtain a system's attributes.

Advantage of the Properties file : 

If the information in a properties file is modified, no recompilation is required: You don't need to recompile the java class if any information in the properties file changes. It is used to keep track of information that needs to be updated frequently.

Let us first create a properties file named “info.properties” having the following content :

user = success

password = determination

Let us now create a java class to read data from the properties file

7. Differentiate between HashMap and HashTable.

Following are the differences between HashMap and HashTable :

problem solving question in java

  • HashMap is a non-synchronized data structure. It is not thread-safe and cannot be shared across many threads without the use of synchronization code, while Hashtable is synchronized. It's thread-safe and can be used by several threads.
  • HashMap supports one null key and numerous null values, whereas Hashtable does not.
  • If thread synchronization is not required, HashMap is often preferable over HashTable.

8. Why does HashMap allow null whereas HashTable does not allow null?

The objects used as keys must implement the hashCode and equals methods in order to successfully save and retrieve objects from a HashTable. These methods cannot be implemented by null because it is not an object. HashMap is a more advanced and improved variant of Hashtable.HashMap was invented after HashTable to overcome the shortcomings of HashTable.

9. How can you synchronize an ArrayList in Java?

An ArrayList can be synchronized using the following two ways :

  • Using Collections.synchronizedList() method: All access to the backup list must be done through the returning list in order to perform serial access. When iterating over the returned list, it is critical that the user manually synchronizes. Example:
  • Using CopyOnWriteArrayList:

Here, a thread-safe variant of ArrayList is created. T represents generic.

All mutative actions (e.g. add, set, remove, etc.) are implemented by generating a separate copy of the underlying array in this thread-safe variation of ArrayList. It accomplishes thread safety by generating a second copy of List, which differs from how vectors and other collections achieve thread-safety.

Even if copyOnWriteArrayList is modified after an iterator is formed, the iterator does not raise ConcurrentModificationException because the iterator is iterating over a separate copy of ArrayList while a write operation is occurring on another copy of ArrayList.

10. Differentiate between Comparable and Comparator in the context of Java.

problem solving question in java

Comparable Comparator
A single sorting sequence is provided by Comparable. To put it another way, we can sort the collection by a single attribute such as id, name, or price. Multiple sorting sequences are available in the Comparator. To put it another way, we can sort the collection based on different criteria such as id, name, and price.
To sort elements, Comparable provides the compareTo() method. To order elements, the Comparator provides the compare() method.
It is present in the java.lang package. It is present in the java.util package.
The original class is affected by Comparable, i.e. the real class is changed.  The original class is unaffected by the comparator, i.e. the real class is unaffected.
The Collections.sort(List) method can be used to sort Comparable type list members. The Collections.sort(List, Comparator) method can be used to sort the list components of the Comparator type.

11. Why does not the Map interface extend the Collection Interface or vice-versa?

If Map extends the Collection Interface, "Key-value pairs" can be the only element type for this type of Collection, although this provides a very limited (and not really useful) Map abstraction. You can't inquire what value a specific key corresponds to, and you can't delete an entry without knowing what value it corresponds to.

The three "Collection view procedures" on Maps represent the fact that Maps can be viewed as Collections (of keys, values, or pairs) (keySet, entrySet, and values). While it is theoretically feasible to see a List as a Map mapping indices to items, this has the unfortunate side effect of changing the Key associated with every element in the List prior to the deleted member. This is the reason why Collection can not be made to extend the Map Interface either.

12. Differentiate between HashMap and TreeMap in the context of Java.

problem solving question in java

HashMap TreeMap
The Java HashMap implementation of the Map interface is based on hash tables. Java TreeMap is a Map interface implementation based on a Tree structure.
The Map, Cloneable, and Serializable interfaces are implemented by HashMap. NavigableMap, Cloneable, and Serializable interfaces are implemented by TreeMap.
Because HashMap does not order on keys, it allows for heterogeneous elements. Because of the sorting, TreeMap allows homogenous values to be used as a key.
HashMap is quicker than TreeMap because it offers O(1) constant-time performance for basic operations such as to get() and put(). TreeMap is slower than HashMap because it performs most operations with O(log(n)) performance, such as add(), remove(), and contains().
A single null key and numerous null values are allowed in HashMap. TreeMap does not allow null keys, however multiple null values are allowed.
To compare keys, it uses the Object class's equals() method. It is overridden by the Map class's equals() function. It compares keys using the compareTo() method.
HashMap does not keep track of any sort of order. The elements are arranged in chronological sequence (ascending).
When we don't need a sorted key-value pair, we should use the HashMap.  When we need a key-value pair in sorted (ascending) order, we should use the TreeMap.

Java Collection Programs

1. given an array in java, convert it to a collection..

We can convert an array to a collection using the asList() method of the Arrays class in Java.

2. Write a program in Java to display the contents of a HashTable using enumeration.

We use the hasMoreElements and the nextElement methods of the Enumeration class to iterate through the HashMap.

We notice that the order of the values is not the same as that of the order in which we inserted the key-value pair in the hashtable. This is because the elements of a Hashtable are not guaranteed to be in any particular sequence. The hashtable's implementation divides values into multiple buckets based on their Hashcode and internal implementation, which means that the same values may appear in a different order on different machines, runs, or versions of the framework. This is because Hashtables are designed to retrieve data by key rather than by order.

3. Write a program to shuffle all the elements of a collection in Java.

We use the shuffle() method of the Collections class. 

4. Write a program in Java to clone a Treeset to another Treeset.

We use the clone() method of the TreeSet class to clone one TreeSet into another.

5. Write a program in java to get the collection view of the values present in a HashMap.

We use the values() function of the HashMap to get the collection view.

6. Write a program in java to join two arraylists into one arraylist.

We use the addAll() method of the ArrayList class to add the contents of both the given arraylists into a new arraylist.

Useful Resources:

Basics of Java

Java Developer Skills

  • Online Java Compiler

Java Developer Salary

ArrayList vs LinkedList

MCQ on Collections in Java

The enumeration returned by Vector is which of the following type :

Which of the following iterators can throw a Concurrent Modification Exception?

What is the default number of segments in a Concurrent Hash Map?

Which one of the following represents the default capacity of Vector?

 In which of the following packages, are all of the collection classes present?

Which of the following methods can be used to convert an object to a list?

When resized, the size of the ArrayList increases by 

Which of the following Map classes must be preferred in a multi-threading environment considering performance constraints?

The Vector class extends which of the following :

Which of the following must be preferred in a multi-threading environment considering performance constraints?

Which of the following guarantees type-safety in a collection?

When resized, the size of the Vector increases by 

Which of the following methods can be used to set every element of the List to a specified value?

Which of the following interfaces is not a part of Java’s collection framework?

Which of the following Set classes must be preferred in a multi-threading environment considering performance constraints?

  • Privacy Policy

instagram-icon

  • Practice Questions
  • Programming
  • System Design
  • Fast Track Courses
  • Online Interviewbit Compilers
  • Online C Compiler
  • Online C++ Compiler
  • Online Javascript Compiler
  • Online Python Compiler
  • Interview Preparation
  • Java Interview Questions
  • Sql Interview Questions
  • Python Interview Questions
  • Javascript Interview Questions
  • Angular Interview Questions
  • Networking Interview Questions
  • Selenium Interview Questions
  • Data Structure Interview Questions
  • Data Science Interview Questions
  • System Design Interview Questions
  • Hr Interview Questions
  • Html Interview Questions
  • C Interview Questions
  • Amazon Interview Questions
  • Facebook Interview Questions
  • Google Interview Questions
  • Tcs Interview Questions
  • Accenture Interview Questions
  • Infosys Interview Questions
  • Capgemini Interview Questions
  • Wipro Interview Questions
  • Cognizant Interview Questions
  • Deloitte Interview Questions
  • Zoho Interview Questions
  • Hcl Interview Questions
  • Highest Paying Jobs In India
  • Exciting C Projects Ideas With Source Code
  • Top Java 8 Features
  • Angular Vs React
  • 10 Best Data Structures And Algorithms Books
  • Best Full Stack Developer Courses
  • Best Data Science Courses
  • Python Commands List
  • Data Scientist Salary
  • Maximum Subarray Sum Kadane’s Algorithm
  • Python Cheat Sheet
  • C++ Cheat Sheet
  • Javascript Cheat Sheet
  • Git Cheat Sheet
  • Java Cheat Sheet
  • Data Structure Mcq
  • C Programming Mcq
  • Javascript Mcq

1 Million +

Java Solved Programs, Problems with Solutions – Java programming

Java solved programs problems with solutions.

Java Solved programs —->  Java is a powerful general-purpose programming language. It is fast, portable and available in all platforms.

This page contains the Java solved programs/examples with solutions, here we are providing most important programs on each topic . These Java examples cover a wide range of programming areas in Computer Science.

Every example program includes the description of the program, Java code as well as output of the program. All examples are compiled and tested on a Windows system.

These examples can be as simple and basic as “Hello World” program to extremely tough and advanced Java programs. Here is the List of Java solved programs/examples with solutions (category wise) and detailed explanation.

Java Solved Programs by categories…….

Java basic solved programs.

  • Java Program to Print Hello World on Screen
  • Java program to Swap two numbers using third variable
  • Java Program to find Addition of two numbers by input value from keyboard
  • Java Program to Swap two numbers without using third variable
  • Java Program Swap Two Numbers using function
  • Java Program to Check entered input is Prime Number or Not
  • Java Program to Check input number is Even or Odd
  • Java Program to find Factorial using While loop
  • Java Program to find Reverse Number using While Loop
  • Java Program to display Fibonacci Series using While Loop
  • Java Program to find GCD (HCF) of Two Numbers
  • Java Program to Check whether Given Number is Armstrong or Not
  • Java Program to find Largest among three Numbers
  • Java Program to find given number is Palindrome or Not
  • Java Program to Find Sum of Digits of given Number
  • Java Program to display n Prime Numbers using Exception Handling
  • Java Program to print Armstrong numbers between desired Range
  • Java Program to Print Floyd’s Triangle using For Loop
  • Java Program to Print Pascal Triangle using Recursion
  • Java Program to Perform Mathematical Operations
  • Java Program to Make a Simple Calculator using switch case
  • Java Program to Calculate Arithmetic Mean of N numbers
  • Java program to convert Fahrenheit to Celsius
  • Java Program to Convert Celsius to Fahrenheit
  • Java Menu Driven Program for If, Switch, While, Do-While and For Loop
  • Java program to multiply N numbers without using * operator

Java Number Solved Programs

  • Java Program to Print Pascal Triangle using For Loop
  • Java program to generate random numbers using Random()
  • Java Program to Find GCD(HCF) and LCM of Two Numbers
  • Java program to find Reverse of a number
  • Java program to find roots of quadratic equation in all cases

Java String Solved Programs

  • Java Program to Print Simple String entered by user
  • Java Program to Find Length of String using length() method
  • Java Program to Compare Two Strings using compareTo() Function
  • Java program to find and display all substrings in string
  • Java Program to reverse any String
  • Java Program to Copy String into Another String
  • Java Program to Append(Concatenate) one string to another string
  • Java Program to Swap Strings using temp variable
  • Java Program to Swap two strings without using temp variable
  • Java Program to Delete or Remove Vowels from string (Manual Method)
  • Java Program to Sort n Strings in Alphabetical Order
  • Java Program to Remove or Delete Vowels from String using Function
  • Java Program to Remove or Delete Words from String using Function
  • Java Program to Delete or Remove Words from String without Function
  • Java Program to Check whether string is palindrome or not using Function
  • Java Program to Check String is palindrome or not using String Buffer
  • Java Program to Check String is Palindrome or not using Recursion
  • Java Program to find Lexicographically smallest and largest substring of length k
  • Java Program to Count frequency or occurrence of all characters in string
  • Java Program to Count frequency of each characters using Buffered Reader
  • Java Program to Count Frequency of Character in String ( 4 Methods )
  • Java Program to Count Frequency or Occurrance of each Word in String

Java Arrays Solved Programs

  • Java Program for Binary Search on Unsorted Array
  • Java Program to input and print n elements in an array
  • Java Program for Addition of Two Matrices
  • Java Program for Subtraction of Two Matrices
  • Java Program to find Transpose Matrix
  • Java Program for Multiplication of Two Matrices
  • Java Program for Linear Search on unsorted array
  • Java Program to Perform Bubble Sort
  • Java Program to perform Selection Sort using static function
  • Java Program to perform Insertion Sort using function
  • Java Program to perform Quick Sort using Static Function

If you found any error or any queries related to the above programs or any questions or reviews , you wanna to ask from us ,you may Contact Us through our contact Page or you can also comment below in the comment section.We will try our best to reach up to you in short interval.

Thanks for reading the post….

No related posts.

guest

nice web but plz add creating account

farouq

please solve the qustion

123n.jpg

Create a menu-based java program for the following queues operations using  linked list :

  • Display/Print

Create a menu-based java program for the following queues operations using array:

nadia

Design a flowchart of the java program that accepts 3 integer values and display the lowest and the highest given value.

macc

hello i need help

Divya

Write a program to input two arrays of size ‘m’ each. Find the sum of the elements of the two arrays in the same index and store it in the 3rd array in reverse order.

tera baap hu mai

wtf………….

Ramesh

Create the class such that it reset the value of the object it is used to null its after uses in all cases using in finally statement in java exception handling

eeee

Enter a four-digit number. Break it down into numbers. Compose a new number in which from the original number all even digits less than 8 are increased by 2, and 8 is replaced by 0(java program)

Zeroo

Write a program that reads in from the user a character (ch), an integer (n) and another character (operator). This operator is an indication of the operation applied to (ch) and (n) entered as follows: – When (operator) character entered is ‘p’ or ‘P’, your program displays the character that comes after (ch) entered in (n) positions. – When (operator) character entered is ‘s’ or ‘S’, your program displays the character that precedes (ch) entered with (n) positions. – When (operator) character entered is ‘m’ or ‘M’, your program displays the character resulting of the multiplication of the value of …  Read more »

anyone know how to solve that question

Lila

implement a multithreaded UDP server and client in java using JDK open source library 1 Client will send a number to server on tcp packet(continuous stream) 2.Server will acknowledge the request with sending back the same number(echo) 3.Client will maintain a data structure which stores un acknowledged numbers from server

Arman

class A { int a; String b; boolean c; A()//default {   a=100; b=”pawan”; c=true; } void Disp() {   System.out.print(a+” “+b+” “+c); } } class B {  public static void main(String []arga){ A r=new A(); r.Disp(); } }

Tasneem

public class TicketCost ( public static void main(String[] args) ( I Declare variables int age; double cost; String msge;

Student Question Bank: Math Questions

Because each question on the Math section deals with different numbers and mathematical scenarios, it's not as simple as the Reading and Writing section to identify exactly what each question stem will look like. You can still use the descriptions in this section to determine which math domains and skills you want to focus on in the Student Question Bank.

Math Questions

Related topics.

  • Skip to main content
  • Keyboard shortcuts for audio player

To help the economy, an Alabama county is betting on home-based child care

Andrea Hsu, photographed for NPR, 11 March 2020, in Washington DC.

MEETING CHILD CARE NEEDS IN TUSCALOOSA

Lakethia Clark stands between a bookcase full of children's books and a toddler bed.

Lakethia Clark stands in her son's bedroom in her home in Tuscaloosa, Alabama. Clark will soon open her own home-based child care business. Claire Harbage/NPR hide caption

TUSCALOOSA, Ala. — Lakethia Clark has spent most of her adult life taking care of children, first at a church day care and later in a child care center. She loves children, but after 15 years, she was getting paid too little and looking after too many kids.

So like many child care workers, she quit. Clark became a housekeeper at a hospital, which paid better, but she missed her old profession.

"It kind of broke my heart," she says. "I miss my babies."

She had long thought about starting her own child care business but always found the licensing process and the startup costs daunting.

Today, however, Clark is getting ready to return to a line of work she loves — on her own terms. She's starting her own small business, caring for as many as six children. And she's doing it right in her own home.

For months, she has been working hard to turn her three-bedroom ranch house and her tree-lined backyard into a children's wonderland.

How have rising prices affected you? What questions do you have about inflation?

How have rising prices affected you? What questions do you have about inflation?

Clark is among the first participants in a program called 3by3. It's the brainchild of Holly Glasgow, a longtime child development educator at Shelton State Community College.

Her vision for the program: dramatically growing the number of small, home-based child care businesses, formally known as family child care homes. It's a program that could prove important for Alabama, by providing more child care options to help boost the state's workforce.

Home-based child care is not new, but Glasgow's exhaustive efforts to provide wrap-around training and guidance, elevating the often invisible child care workforce, have drawn attention and even visitors from states including Colorado and California.

To go to work, parents need child care

The initiative is one of many being piloted around the U.S. as federal and state governments, along with the business community, have come to recognize child care as essential to economic growth.

A bookshelf in Clark's home holds a selection of children's picture books.

Clark has a collection of books in her son's room and will add more once she begins caring for kids out of her home. Claire Harbage/NPR hide caption

It's an especially pressing issue in Alabama, a state with one of the country's lowest labor force participation rates.

To get her program going, Glasgow got creative, "blending and braiding" funding from a number of sources, including the federal Workforce Innovation and Opportunity Act, which aims to help job seekers move into high-quality careers.

Other funders include the Chamber of Commerce of West Alabama as well as the Women's Foundation of Alabama, a philanthropic organization focused on accelerating economic opportunity for women.

"It's an interesting narrative shift, that child care isn't just on the mom," says Lillian Brand, vice president of external affairs at the Women’s Foundation of Alabama. "It's really on the entire economy in order to keep us all moving forward."

D'Koya Mathis holds her 2-year-old daughter Zharia's hand as they walk into Ms. Pat's Child Care & Development Center in Madison, Ala.

An Alabama manufacturer shows how to retain working moms: child care

Child care needs are severely unmet.

The need for more child care is evident in the numbers. Glasgow estimates Tuscaloosa County has over 12,000 children under age 5 but just over 3,000 child care spots.

Some of those spots are at the community-based pre-K center on the campus of Shelton State, which Glasgow oversees.

While a couple of kids paint pictures at an arts and crafts station, others check in on caterpillars on their journey of metamorphosis. Across the room, more children take turns playing customer and shopkeeper in a make-believe flower shop.

"Happy, healthy, safe is our goal," says Glasgow.

Holly Glasgow sits at a table with three children in the pre-K program she directs on the campus of Shelton State Community College in Tuscaloosa.

Holly Glasgow talks to children in the pre-K program she directs on the campus of Shelton State Community College in Tuscaloosa. Given the high cost of building child care centers like this one, Glasgow is focused on developing another model of child care — family child care homes. Claire Harbage/NPR hide caption

She would love for every young child in Alabama to have a spot at a center like this one. But she knows that's impossible. The main impediment is cost.

When an Alabama nonprofit foundation approached her with a fundraising proposal and asked how many child care centers could be built with $10 million, she told them: less than one.

"They were floored," she says.

So instead, Glasgow is focusing her efforts on family child care homes. She believes these small businesses can achieve the same level of quality as larger centers but at a much lower cost and in a way that may better suit Tuscaloosa's working parents.

A diversity of child care needs

Among the top employers in this region are hospitals and manufacturers, including Mercedes-Benz and the food company Smucker's, which has been recruiting workers for a brand-new plant not far away.

Glasgow points out that these employers need workers around the clock, but few child care providers offer care in the evenings, on weekends and overnight.

$400-a-month pandemic bonuses were life-changing for child care workers. That's over

$400-a-month pandemic bonuses were life-changing for child care workers. That's over

Family child care homes, which are typically run by women who care for their own children and a handful of others, can be more flexible with their hours. They can also provide a more homelike environment, which many parents who work overnight shifts prefer, Glasgow says.

"Your kids still go to bed in a bedroom," she says. "They still have breakfast at the kitchen table."

"Can't wait"

The first cohort of 3by3 participants wrapped up their coursework this spring. This included five intensive weeks of classes on child development, health and safety, and how to run a small business.

On top of that, there are the home visits.

Glasgow stands on the sidewalk outside Clark's home on a corner lot in a Tuscaloosa neighborhood.

Glasgow visits the home of Lakethia Clark to help her reconfigure her living quarters into play areas for children. Claire Harbage/NPR hide caption

On a recent sunny morning, Glasgow headed to Clark's home on a corner lot to help her reimagine her living quarters as play and learning spaces and to ensure that everything is up to code.

Glasgow works quickly, whipping out a laser measuring tool as she sketches a floor plan.

"Miss Holly ... that lady is awesome," says a smiling Clark.

Clark lays out her vision for her formal living room: one sofa moved to the side, another one taken out to make room for children's tables, a couple of carpets, and shelves for toys and books.

"I can't wait to put stuff on the walls," she says.

Lakethia Clark is planning to start a childcare facility in her home in Tuscaloosa, Alabama.

Clark jumped at the opportunity to open her own home-based child care business. She expects to receive her license sometime this summer. Claire Harbage/NPR hide caption

Glasgow has $5,000 to $10,000 to spend on furniture and supplies for each new family child care home. Paths for Success, the nonprofit foundation that originally approached Glasgow about building child care centers, provides the health and safety materials, including fire extinguishers, hardwired smoke detectors, flashlights, and cribs and cots.

It's the assist Clark needed to get her business off the ground. Before now, she says, her finances always got in the way.

Although she had worked in child care for years, Clark's hourly wage never topped $13.50 an hour. For a while, she worked a second job at Taco Casa to save enough money for the down payment on her house.

Now, she is looking forward to becoming a small-business owner. There are tax benefits, including being able to deduct part of her mortgage as a business expense. She may qualify for a new Alabama tax credit for child care providers.

Best of all, she'll get to be her own boss.

Glasgow sits with Clark in Clark's living room, holding a pencil and clipboard as she begins to work on a floor plan, transforming the room into a play and learning space for kids.

Glasgow works with Clark to reimagine Clark's living room as a play and learning space. Claire Harbage/NPR hide caption

Looking out over her spacious, shady backyard, she imagines children covering her wooden fence with chalk drawings, something she loved watching kids do at her last child care job.

"The owners of the day care used to get so mad," she says, laughing. "It's just artwork! It's going to disappear."

Already, parents she knew from her old job have been calling her, hoping to send her their younger kids.

"They know what type of worker I was," she says. "They know I always put the kids first."

With all her paperwork submitted, Clark is hoping to get final clearance this summer, in time to welcome kids into her home.

  • women in the workforce
  • home-based care
  • Practice Sorting
  • MCQs on Sorting
  • Tutorial on Sorting
  • Bubble Sort
  • Insertion Sort
  • Selection Sort
  • Sorting Complexities
  • Counting Sort
  • Bucket Sort
  • Bitonic Sort
  • Uses of Sorting Algorithm

Insertion Sort Algorithm

Insertion sort in different languages.

  • C Program For Insertion Sort
  • C++ Program For Insertion Sort
  • Insertion sort using C++ STL
  • Java Program for Insertion Sort
  • Python Program for Insertion Sort
  • Binary Insertion Sort

Binary Insertion Sort in Different languages

  • C Program for Binary Insertion Sort
  • Python Program for Binary Insertion Sort

Recursive Insertion Sort in Different languages

  • Java Program for Recursive Insertion Sort

Insertion Sort on Linked List

  • Javascript Program For Insertion Sort In A Singly Linked List
  • Insertion sort to sort even and odd positioned elements in different orders
  • Sorting by combining Insertion Sort and Merge Sort algorithms

Problem on Insertion Sort

  • Sorting an Array in Bash using Insertion Sort
  • Given a linked list which is sorted, how will you insert in sorted way
  • Count swaps required to sort an array using Insertion Sort
  • How to visualize selection and insertion sort using Tkinter in Python?
  • Sorting algorithm visualization : Insertion Sort

Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is a stable sorting algorithm, meaning that elements with equal values maintain their relative order in the sorted output.

Insertion sort is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. Then, you pick a card from the unsorted group and put it in the right place in the sorted group.

Insertion Sort Algorithm:

Insertion sort is a simple sorting algorithm that works by building a sorted array one element at a time. It is considered an ” in-place ” sorting algorithm, meaning it doesn’t require any additional memory space beyond the original array.

To achieve insertion sort, follow these steps:

  • We have to start with second element of the array as first element in the array is assumed to be sorted.
  • Compare second element with the first element and check if the second element is smaller then swap them.
  • Move to the third element and compare it with the second element, then the first element and swap as necessary to put it in the correct position among the first three elements.
  • Continue this process, comparing each element with the ones before it and swapping as needed to place it in the correct position among the sorted elements.
  • Repeat until the entire array is sorted.

Working of Insertion Sort Algorithm:

Consider an array having elements : {23, 1, 10, 5, 2} First Pass: Current element is 23 The first element in the array is assumed to be sorted. The sorted part until 0th index is : [23] Second Pass: Compare 1 with 23 (current element with the sorted part). Since 1 is smaller, insert 1 before 23 . The sorted part until 1st index is: [1, 23] Third Pass: Compare 10 with 1 and 23 (current element with the sorted part). Since 10 is greater than 1 and smaller than 23 , insert 10 between 1 and 23 . The sorted part until 2nd index is: [1, 10, 23] Fourth Pass: Compare 5 with 1 , 10 , and 23 (current element with the sorted part). Since 5 is greater than 1 and smaller than 10 , insert 5 between 1 and 10 . The sorted part until 3rd index is : [1, 5, 10, 23] Fifth Pass: Compare 2 with 1, 5, 10 , and 23 (current element with the sorted part). Since 2 is greater than 1 and smaller than 5 insert 2 between 1 and 5 . The sorted part until 4th index is: [1, 2, 5, 10, 23] Final Array: The sorted array is: [1, 2, 5, 10, 23]

To deepen your understanding of sorting algorithms like insertion sort and other essential data structures, consider enrolling in our comprehensive course, Tech Interview 101 – From DSA to System Design . This course covers data structures and algorithms from basic to advanced levels , ensuring you have a solid foundation to excel in technical exams and interviews. Building this knowledge is crucial for your success in the tech industry.

Implementation of Insertion Sort:

Time Complexity: O(N^2) Auxiliary Space: O(1)

Complexity Analysis of Insertion Sort :

Time complexity of insertion sort.

  • Best case: O(n) , If the list is already sorted, where n is the number of elements in the list.
  • Average case: O(n 2 ) , If the list is randomly ordered
  • Worst case: O(n 2 ) , If the list is in reverse order

Space Complexity of Insertion Sort

  • Auxiliary Space: O(1), Insertion sort requires O(1) additional space, making it a space-efficient sorting algorithm.

Advantages of Insertion Sort:

  • Simple and easy to implement.
  • Stable sorting algorithm.
  • Efficient for small lists and nearly sorted lists.
  • Space-efficient.

Disadvantages of Insertion Sort:

  • Inefficient for large lists.
  • Not as efficient as other sorting algorithms (e.g., merge sort, quick sort) for most cases.

Applications of Insertion Sort:

Insertion sort is commonly used in situations where:

  • The list is small or nearly sorted.
  • Simplicity and stability are important.

Frequently Asked Questions on Insertion Sort

Q1. What are the Boundary Cases of the Insertion Sort algorithm?

Insertion sort takes the maximum time to sort if elements are sorted in reverse order. And it takes minimum time (Order of n) when elements are already sorted.

Q2. What is the Algorithmic Paradigm of the Insertion Sort algorithm?

The Insertion Sort algorithm follows an incremental approach.

Q3. Is Insertion Sort an in-place sorting algorithm?

Yes, insertion sort is an in-place sorting algorithm.

Q4. Is Insertion Sort a stable algorithm?

Yes, insertion sort is a stable sorting algorithm.

Q5. When is the Insertion Sort algorithm used?

Insertion sort is used when number of elements is small. It can also be useful when the input array is almost sorted, and only a few elements are misplaced in a complete big array.

Please Login to comment...

Similar reads.

  • Juniper Networks
  • MAQ Software

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Problem Solving Skills in Java Programming

    problem solving question in java

  2. Problem Solving Modules in Java

    problem solving question in java

  3. Problem Solving in Java

    problem solving question in java

  4. Enhancing Problem-Solving Skills in Java Programming: A Comprehensive Guide

    problem solving question in java

  5. Problem Solving in Java Part 1-Introduction

    problem solving question in java

  6. Java Problem Solving Tutorial: Left to Right Evaluation

    problem solving question in java

VIDEO

  1. Problem solving question #13 of #javascript #development #shorts

  2. Problem solving question #6 of #javascript #shorts

  3. 2024 Year 6 SATs Revision: Area and Volume (Problem Solving)

  4. Problem solving question #12 of #javascript #shorts #developer

  5. Compound Measure 3 Area Force and Pressure Part 5 Problem Solving

  6. Java Interview Question and Answers

COMMENTS

  1. Java Exercises

    Write Hello World Program in Java. The solution to the Problem is mentioned below: Java // Java Program to Print ... We hope these exercises have helped you understand Java better and you can solve beginner to advanced-level questions on Java programming. Solving these Java programming exercise questions will not only help you master theory ...

  2. Java programming Exercises, Practice, Solution

    The best way we learn anything is by practice and exercise questions. Here you have the opportunity to practice the Java programming language concepts by solving the exercises starting from basic to more complex exercises. It is recommended to do these exercises by yourself first before checking the solution.

  3. Top 50 Java Programs from Coding Interviews

    Here is a big list of Java programs for Job Interviews. As I said, it includes questions from problem-solving, linked list, array, string, matrix, bitwise operators and other miscellaneous parts of programming. Once you are gone through these questions, you can handle a good number of questions on real Job interviews. 1. Fibonacci series

  4. 200+ Core Java Interview Questions and Answers (2024)

    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. In this article, we will provide 200+ Core Java Interview Questions tailored for both freshers and experienced professionals with 3, 5, and 8 years of experience.

  5. Problems

    Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

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

  7. Solve Java

    Join over 23 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.

  8. Practice Java

    Complete your Java coding practice with our online Java practice course on CodeChef. Solve over 180 coding problems and challenges to get better at Java. Courses. Learn Python 10 courses. Learn C++ 9 ... Multiple Choice Question: Easy: CodeChef Learn Problem Solving: 287: Multiple Choice Question: Easy: Learning SQL: 339: Multiple Choice ...

  9. Java 8 Coding and Programming Interview Questions and Answers

    It has been 8 years since Java 8 was released. I have already shared the Java 8 Interview Questions and Answers and also Java 8 Stream API Interview Questions and Answers.You can also find the Java 8 — Real-Time Coding Interview Questions and Answers.. In this tutorial, I will be sharing the top Java 8 coding and programming interview questions and answers.

  10. Java Interview Questions and Programming Examples

    Java Problem Solving Questions. This skill corresponds to the developer's ability to evaluate and resolve a problem by writing an efficient algorithm in Java. Any developers should be able to solve simple problems but advanced analytical skills and logical reasoning are essential when your are hiring Java R&D developers. Problem Solving ...

  11. Ace the top 15 Java algorithm questions for coding interviews

    Algorithm-based questions are a staple of any modern coding interview, as they demonstrate your problem-solving and critical thinking skills. To make sure you don't get caught off guard in your next Java interview, we've put together 15 of the most common algorithm coding questions used by most tech companies and recruiters across the industry. ...

  12. Java Programs

    In this article, we dealt with a variety of Java programming questions categorized as basic programs, control statements, Arrays, Strings, OOPs, and much more that are frequently asked in interviews and exams. Each Java program will give you a different approach to solving a particular problem in Java.

  13. 800+ Java Practice Challenges // Edabit

    How Edabit Works. This is an introduction to how challenges on Edabit work. In the Code tab above you'll see a starter function that looks like this: public static boolean returnTrue () { } All you have to do is type return true; between the curly braces { } and then click the Check button. If you did this correctly, the button will turn re ...

  14. 10 Java Interview Questions You Should Know

    These questions cover more specific concepts and language-specific knowledge, and are also meant to be solved in a collaborative IDE. You can access the sample inputs, sample outputs, and base code for each question by clicking the solve problem links. Java Regex. Solve Problem. Write a class called MyRegex which will contain a string pattern.

  15. 51 Java Programming Interview Questions (And Sample Answers)

    Related: Java Interview Questions for Experienced Programmers 13. How do you reverse a string in Java? There's no reverse utility provided in Java. Hiring managers might ask this question to determine your knowledge of Java and your problem-solving skills. You can create a character array from the string and iterate it from the end to the ...

  16. Java Interview Questions and Answers

    Java Interview Questions and Answers. The pressure to perform well in an interview can feel overwhelming. Despite your knowledge and experience, nervousness could get in the way of putting your best foot forward. But, if you know the questions to expect and how to answer them, you can relax and focus on showcasing what you know and what you can do.

  17. Java Practice Programs

    Java is a popular programming language that is used to develop a wide variety of applications. One of the best ways to learn Java is to practice writing programs. Many resources are available online and in libraries to help you find Java practice programs. When practising Java programs, it is important to focus on understanding the concepts ...

  18. Top 53 Java Programs for Coding and Programming Interviews

    1. For a given array of integers (positive and negative) find the largest sum of a contiguous sequence. 2. Algorithm: Implement a queue using 2 stacks (solution) 3. Algorithm: Integer division without the division operator (/) (solution) 4. How to print All permutations of a Given String in Java ( solution) 5.

  19. Java Interview Programming Questions and Answers

    Java Interview Programming Questions and Answers. Java is an object-oriented programming language and computing platform first released by Sun Microsystems in 1995. During an interview it does not matter whatever framework you know, the initial stage of the interview is always based on the programming sense, coding skills, and problem-solving ...

  20. 15 Common Problem-Solving Interview Questions

    Here are a few examples of technical problem-solving questions: 1. Mini-Max Sum. This well-known challenge, which asks the interviewee to find the maximum and minimum sum among an array of given numbers, is based on a basic but important programming concept called sorting, as well as integer overflow.

  21. Java Interview Prep: Top 5 Coding Problems

    This article delves into five common Java interview problems, providing both starter code and detailed solutions to enhance your understanding and problem-solving skills. Array Rotation. Problem ...

  22. 50+ Important Java Interview Questions and Answers to Know

    More Important Basic Questions for Java Developers. Keep in mind that, although Java is already an object-oriented programming language, you may want to ask questions about object-oriented programming that are more theoretical, conceptual, and outside general Java programming. ... problem-solving, time management, and more. You can also explore ...

  23. Java : Switch Statement

    Java : Switch Statement - Exercises and Solution. 1. Write a program to read a weekday number and print weekday name using switch statement. View Solution. 2. Write a program to read gender (M/F) and print the corresponding gender using a switch statement. View Solution.

  24. Top Java Collections Interview Questions (2024)

    Before you leave, take this Java Collections Interview Questions interview guide with you. Download PDF exit . Get a Free ... Before we use a collection, we must choose the most relevant collection for the problem we are seeking to solve. If we pick the wrong one, our program may still run, but it will be inefficient. On the other hand, if we ...

  25. Java Solved Programs, Problems with Solutions

    Java Solved programs —-> Java is a powerful general-purpose programming language. It is fast, portable and available in all platforms. This page contains the Java solved programs/examples with solutions, here we are providing most important programs on each topic. These Java examples cover a wide range of programming areas in Computer Science.

  26. Student Question Bank: Math Questions

    Domain: Problem-Solving and Data Analysis Skill: Evaluating statistical claims—Observational studies and experiments Solve real-world and mathematical problems about area, perimeter, surface area, or volume of a geometric figure, and use scale factors to calculate changes to length and area.

  27. To help the economy, Alabama is betting on home-based child care

    A project in Alabama seeks to drastically grow the number of home-based child care options. It could help the state's workforce, especially during nontraditional hours.

  28. Insertion Sort Algorithm

    Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is a stable sorting algorithm, meaning that elements with equal values maintain their relative order in the sorted output.. Insertion sort is like sorting playing cards in your hands.