Java Coding Practice

java collection problem solving questions

What kind of Java practice exercises are there?

How to solve these java coding challenges, why codegym is the best platform for your java code practice.

  • Tons of versatile Java coding tasks for learners with any background: from Java Syntax and Core Java topics to Multithreading and Java Collections
  • The support from the CodeGym team and the global community of learners (“Help” section, programming forum, and chat)
  • The modern tool for coding practice: with an automatic check of your solutions, hints on resolving the tasks, and advice on how to improve your coding style

java collection problem solving questions

Click on any topic to practice Java online right away

Practice java code online with codegym.

In Java programming, commands are essential instructions that tell the computer what to do. These commands are written in a specific way so the computer can understand and execute them. Every program in Java is a set of commands. At the beginning of your Java programming practice , it’s good to know a few basic principles:

  • In Java, each command ends with a semicolon;
  • A command can't exist on its own: it’s a part of a method, and method is part of a class;
  • Method (procedure, function) is a sequence of commands. Methods define the behavior of an object.

Here is an example of the command:

The command System.out.println("Hello, World!"); tells the computer to display the text inside the quotation marks.

If you want to display a number and not text, then you do not need to put quotation marks. You can simply write the number. Or an arithmetic operation. For example:

Command to display the number 1.

A command in which two numbers are summed and their sum (10) is displayed.

As we discussed in the basic rules, a command cannot exist on its own in Java. It must be within a method, and a method must be within a class. Here is the simplest program that prints the string "Hello, World!".

We have a class called HelloWorld , a method called main() , and the command System.out.println("Hello, World!") . You may not understand everything in the code yet, but that's okay! You'll learn more about it later. The good news is that you can already write your first program with the knowledge you've gained.

Attention! You can add comments in your code. Comments in Java are lines of code that are ignored by the compiler, but you can mark with them your code to make it clear for you and other programmers.

Single-line comments start with two forward slashes (//) and end at the end of the line. In example above we have a comment //here we print the text out

You can read the theory on this topic here , here , and here . But try practicing first!

Explore the Java coding exercises for practicing with commands below. First, read the conditions, scroll down to the Solution box, and type your solution. Then, click Verify (above the Conditions box) to check the correctness of your program.

java collection problem solving questions

The two main types in Java are String and int. We store strings/text in String, and integers (whole numbers) in int. We have already used strings and integers in previous examples without explicit declaration, by specifying them directly in the System.out.println() operator.

In the first case “I am a string” is a String in the second case 5 is an integer of type int. However, most often, in order to manipulate data, variables must be declared before being used in the program. To do this, you need to specify the type of the variable and its name. You can also set a variable to a specific value, or you can do this later. Example:

Here we declared a variable called a but didn't give it any value, declared a variable b and gave it the value 5 , declared a string called s and gave it the value Hello, World!

Attention! In Java, the = sign is not an equals sign, but an assignment operator. That is, the variable (you can imagine it as an empty box) is assigned the value that is on the right (you can imagine that this value was put in the empty box).

We created an integer variable named a with the first command and assigned it the value 5 with the second command.

Before moving on to practice, let's look at an example program where we will declare variables and assign values to them:

In the program, we first declared an int variable named a but did not immediately assign it a value. Then we declared an int variable named b and "put" the value 5 in it. Then we declared a string named s and assigned it the value "Hello, World!" After that, we assigned the value 2 to the variable a that we declared earlier, and then we printed the variable a, the sum of the variables a and b, and the variable s to the screen

This program will display the following:

We already know how to print to the console, but how do we read from it? For this, we use the Scanner class. To use Scanner, we first need to create an instance of the class. We can do this with the following code:

Once we have created an instance of Scanner, we can use the next() method to read input from the console or nextInt() if we should read an integer.

The following code reads a number from the console and prints it to the console:

Here we first import a library scanner, then ask a user to enter a number. Later we created a scanner to read the user's input and print the input out.

This code will print the following output in case of user’s input is 5:

More information about the topic you could read here , here , and here .

See the exercises on Types and keyboard input to practice Java coding:

Conditions and If statements in Java allow your program to make decisions. For example, you can use them to check if a user has entered a valid password, or to determine whether a number is even or odd. For this purpose, there’s an 'if/else statement' in Java.

The syntax for an if statement is as follows:

Here could be one or more conditions in if and zero or one condition in else.

Here's a simple example:

In this example, we check if the variable "age" is greater than or equal to 18. If it is, we print "You are an adult." If not, we print "You are a minor."

Here are some Java practice exercises to understand Conditions and If statements:

In Java, a "boolean" is a data type that can have one of two values: true or false. Here's a simple example:

The output of this program is here:

In addition to representing true or false values, booleans in Java can be combined using logical operators. Here, we introduce the logical AND (&&) and logical OR (||) operators.

  • && (AND) returns true if both operands are true. In our example, isBothFunAndEasy is true because Java is fun (isJavaFun is true) and coding is not easy (isCodingEasy is false).
  • || (OR) returns true if at least one operand is true. In our example, isEitherFunOrEasy is true because Java is fun (isJavaFun is true), even though coding is not easy (isCodingEasy is false).
  • The NOT operator (!) is unary, meaning it operates on a single boolean value. It negates the value, so !isCodingEasy is true because it reverses the false value of isCodingEasy.

So the output of this program is:

More information about the topic you could read here , and here .

Here are some Java exercises to practice booleans:

With loops, you can execute any command or a block of commands multiple times. The construction of the while loop is:

Loops are essential in programming to execute a block of code repeatedly. Java provides two commonly used loops: while and for.

1. while Loop: The while loop continues executing a block of code as long as a specified condition is true. Firstly, the condition is checked. While it’s true, the body of the loop (commands) is executed. If the condition is always true, the loop will repeat infinitely, and if the condition is false, the commands in a loop will never be executed.

In this example, the code inside the while loop will run repeatedly as long as count is less than or equal to 5.

2. for Loop: The for loop is used for iterating a specific number of times.

In this for loop, we initialize i to 1, specify the condition i <= 5, and increment i by 1 in each iteration. It will print "Count: 1" to "Count: 5."

Here are some Java coding challenges to practice the loops:

An array in Java is a data structure that allows you to store multiple values of the same type under a single variable name. It acts as a container for elements that can be accessed using an index.

What you should know about arrays in Java:

  • Indexing: Elements in an array are indexed, starting from 0. You can access elements by specifying their index in square brackets after the array name, like myArray[0] to access the first element.
  • Initialization: To use an array, you must declare and initialize it. You specify the array's type and its length. For example, to create an integer array that can hold five values: int[] myArray = new int[5];
  • Populating: After initialization, you can populate the array by assigning values to its elements. All elements should be of the same data type. For instance, myArray[0] = 10; myArray[1] = 20;.
  • Default Values: Arrays are initialized with default values. For objects, this is null, and for primitive types (int, double, boolean, etc.), it's typically 0, 0.0, or false.

In this example, we create an integer array, assign values to its elements, and access an element using indexing.

In Java, methods are like mini-programs within your main program. They are used to perform specific tasks, making your code more organized and manageable. Methods take a set of instructions and encapsulate them under a single name for easy reuse. Here's how you declare a method:

  • public is an access modifier that defines who can use the method. In this case, public means the method can be accessed from anywhere in your program.Read more about modifiers here .
  • static means the method belongs to the class itself, rather than an instance of the class. It's used for the main method, allowing it to run without creating an object.
  • void indicates that the method doesn't return any value. If it did, you would replace void with the data type of the returned value.

In this example, we have a main method (the entry point of the program) and a customMethod that we've defined. The main method calls customMethod, which prints a message. This illustrates how methods help organize and reuse code in Java, making it more efficient and readable.

In this example, we have a main method that calls the add method with two numbers (5 and 3). The add method calculates the sum and returns it. The result is then printed in the main method.

All composite types in Java consist of simpler ones, up until we end up with primitive types. An example of a primitive type is int, while String is a composite type that stores its data as a table of characters (primitive type char). Here are some examples of primitive types in Java:

  • int: Used for storing whole numbers (integers). Example: int age = 25;
  • double: Used for storing numbers with a decimal point. Example: double price = 19.99;
  • char: Used for storing single characters. Example: char grade = 'A';
  • boolean: Used for storing true or false values. Example: boolean isJavaFun = true;
  • String: Used for storing text (a sequence of characters). Example: String greeting = "Hello, World!";

Simple types are grouped into composite types, that are called classes. Example:

We declared a composite type Person and stored the data in a String (name) and int variable for an age of a person. Since composite types include many primitive types, they take up more memory than variables of the primitive types.

See the exercises for a coding practice in Java data types:

String is the most popular class in Java programs. Its objects are stored in a memory in a special way. The structure of this class is rather simple: there’s a character array (char array) inside, that stores all the characters of the string.

String class also has many helper classes to simplify working with strings in Java, and a lot of methods. Here’s what you can do while working with strings: compare them, search for substrings, and create new substrings.

Example of comparing strings using the equals() method.

Also you can check if a string contains a substring using the contains() method.

You can create a new substring from an existing string using the substring() method.

More information about the topic you could read here , here , here , here , and here .

Here are some Java programming exercises to practice the strings:

In Java, objects are instances of classes that you can create to represent and work with real-world entities or concepts. Here's how you can create objects:

First, you need to define a class that describes the properties and behaviors of your object. You can then create an object of that class using the new keyword like this:

It invokes the constructor of a class.If the constructor takes arguments, you can pass them within the parentheses. For example, to create an object of class Person with the name "Jane" and age 25, you would write:

Suppose you want to create a simple Person class with a name property and a sayHello method. Here's how you do it:

In this example, we defined a Person class with a name property and a sayHello method. We then created two Person objects (person1 and person2) and used them to represent individuals with different names.

Here are some coding challenges in Java object creation:

Static classes and methods in Java are used to create members that belong to the class itself, rather than to instances of the class. They can be accessed without creating an object of the class.

Static methods and classes are useful when you want to define utility methods or encapsulate related classes within a larger class without requiring an instance of the outer class. They are often used in various Java libraries and frameworks for organizing and providing utility functions.

You declare them with the static modifier.

Static Methods

A static method is a method that belongs to the class rather than any specific instance. You can call a static method using the class name, without creating an object of that class.

In this example, the add method is static. You can directly call it using Calculator.add(5, 3)

Static Classes

In Java, you can also have static nested classes, which are classes defined within another class and marked as static. These static nested classes can be accessed using the outer class's name.

In this example, Student is a static nested class within the School class. You can access it using School.Student.

More information about the topic you could read here , here , here , and here .

See below the exercises on Static classes and methods in our Java coding practice for beginners:

Java Collections Interview Questions

Last updated: January 8, 2024

java collection problem solving questions

  • Java Collections

announcement - icon

It's finally here:

>> The Road to Membership and Baeldung Pro .

Going into ads, no-ads reading , and bit about how Baeldung works if you're curious :)

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page .

You can also ask questions and leave feedback on the Azure Container Apps GitHub page .

Java applications have a notoriously slow startup and a long warmup time. The CRaC (Coordinated Restore at Checkpoint) project from OpenJDK can help improve these issues by creating a checkpoint with an application's peak performance and restoring an instance of the JVM to that point.

To take full advantage of this feature, BellSoft provides containers that are highly optimized for Java applications. These package Alpaquita Linux (a full-featured OS optimized for Java and cloud environment) and Liberica JDK (an open-source Java runtime based on OpenJDK).

These ready-to-use images allow us to easily integrate CRaC in a Spring Boot application:

Improve Java application performance with CRaC support

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page .

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page .

Whether you're just starting out or have years of experience, Spring Boot is obviously a great choice for building a web application.

Jmix builds on this highly powerful and mature Boot stack, allowing devs to build and deliver full-stack web applications without having to code the frontend. Quite flexibly as well, from simple web GUI CRUD applications to complex enterprise solutions.

Concretely, The Jmix Platform includes a framework built on top of Spring Boot, JPA, and Vaadin , and comes with Jmix Studio, an IntelliJ IDEA plugin equipped with a suite of developer productivity tools.

The platform comes with interconnected out-of-the-box add-ons for report generation, BPM, maps, instant web app generation from a DB, and quite a bit more:

>> Become an efficient full-stack developer with Jmix

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema .

The way it does all of that is by using a design model , a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

>> Take a look at DBSchema

Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.

Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.

Write code that works the way you meant it to:

>> CodiumAI. Meaningful Code Tests for Busy Devs

The AI Assistant to boost Boost your productivity writing unit tests - Machinet AI .

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code. And, the AI Chat crafts code and fixes errors with ease, like a helpful sidekick.

Simplify Your Coding Journey with Machinet AI :

>> Install Machinet AI in your IntelliJ

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

Download the E-book

Do JSON right with Jackson

Get the most out of the Apache HTTP Client

Get Started with Apache Maven:

Working on getting your persistence layer right with Spring?

Explore the eBook

Building a REST API with Spring?

Get started with Spring and Spring Boot, through the Learn Spring course:

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Get started with Spring and Spring Boot, through the reference Learn Spring course:

>> LEARN SPRING

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth , to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project .

You can explore the course here:

>> Learn Spring Security

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot .

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

1. Introduction

Java Collections is a topic often brought up on technical interviews for Java developers. This article reviews some important questions that are asked most often and may be tricky to get right.

2. Questions

Q1. describe the collections type hierarchy. what are the main interfaces, and what are the differences between them.

The Iterable interface represents any collection that can be iterated using the for-each loop. The Collection interface inherits from Iterable and adds generic methods for checking if an element is in a collection, adding and removing elements from the collection, determining its size etc.

The List , Set , and Queue interfaces inherit from the Collection interface.

List is an ordered collection, and its elements can be accessed by their index in the list.

Set is an unordered collection with distinct elements, similar to the mathematical notion of a set.

Queue is a collection with additional methods for adding, removing and examining elements, useful for holding elements prior to processing.

Map interface is also a part of the collection framework, yet it does not extend Collection . This is by design, to stress the difference between collections and mappings which are hard to gather under a common abstraction. The Map interface represents a key-value data structure with unique keys and no more than one value for each key.

Q2. Describe Various Implementations of the Map Interface and Their Use Case Differences.

One of the most often used implementations of the Map interface is the HashMap . It is a typical hash map data structure that allows accessing elements in constant time, or O(1), but does not preserve order and is not thread-safe .

To preserve insertion order of elements, you can use the LinkedHashMap class which extends the HashMap and additionally ties the elements into a linked list, with foreseeable overhead.

The TreeMap class stores its elements in a red-black tree structure, which allows accessing elements in logarithmic time, or O(log(n)). It is slower than the HashMap for most cases, but it allows keeping the elements in order according to some Comparator .

The ConcurrentHashMap is a thread-safe implementation of a hash map. It provides full concurrency of retrievals (as the get operation does not entail locking) and high expected concurrency of updates.

The Hashtable class has been in Java since version 1.0. It is not deprecated but is mostly considered obsolete. It is a thread-safe hash map, but unlike ConcurrentHashMap , all its methods are simply synchronized , which means that all operations on this map block, even retrieval of independent values.

Q3. Explain the Difference Between Linkedlist and Arraylist.

ArrayList is an implementation of the List interface that is based on an array. ArrayList internally handles resizing of this array when the elements are added or removed. You can access its elements in constant time by their index in the array. However, inserting or removing an element infers shifting all consequent elements which may be slow if the array is huge and the inserted or removed element is close to the beginning of the list.

LinkedList is a doubly-linked list: single elements are put into Node objects that have references to previous and next Node . This implementation may appear more efficient than ArrayList if you have lots of insertions or deletions in different parts of the list, especially if the list is large.

In most cases, however, ArrayList outperforms LinkedList . Even elements shifting in ArrayList , while being an O(n) operation, is implemented as a very fast System.arraycopy() call. It can even appear faster than the LinkedList ‘s O(1) insertion which requires instantiating a Node object and updating multiple references under the hood. LinkedList also can have a large memory overhead due to a creation of multiple small Node objects.

Q4. What Is the Difference Between Hashset and Treeset?

Both HashSet and TreeSet classes implement the Set interface and represent sets of distinct elements. Additionally, TreeSet implements the NavigableSet interface. This interface defines methods that take advantage of the ordering of elements.

HashSet is internally based on a HashMap , and TreeSet is backed by a TreeMap instance, which defines their properties: HashSet does not keep elements in any particular order. Iteration over the elements in a HashSet produces them in a shuffled order. TreeSet , on the other hand, produces elements in order according to some predefined Comparator .

Q5. How Is Hashmap Implemented in Java? How Does Its Implementation Use Hashcode and Equals Methods of Objects? What Is the Time Complexity of Putting and Getting an Element from Such Structure?

The HashMap class represents a typical hash map data structure with certain design choices.

The HashMap is backed by a resizable array that has a size of power-of-two. When the element is added to a HashMap , first its hashCode is calculated (an int value). Then a certain number of lower bits of this value are used as an array index. This index directly points to the cell of the array (called a bucket) where this key-value pair should be placed. Accessing an element by its index in an array is a very fast O(1) operation, which is the main feature of a hash map structure.

A hashCode is not unique, however, and even for different hashCodes , we may receive the same array position. This is called a collision. There is more than one way of resolving collisions in the hash map data structures. In Java’s HashMap , each bucket actually refers not to a single object, but to a red-black tree of all objects that landed in this bucket (prior to Java 8, this was a linked list).

So when the HashMap has determined the bucket for a key, it has to traverse this tree to put the key-value pair in its place. If a pair with such key already exists in the bucket, it is replaced with a new one.

To retrieve the object by its key, the HashMap again has to calculate the hashCode for the key, find the corresponding bucket, traverse the tree, call equals on keys in the tree and find the matching one.

HashMap has O(1) complexity, or constant-time complexity, of putting and getting the elements. Of course, lots of collisions could degrade the performance to O(log(n)) time complexity in the worst case, when all elements land in a single bucket. This is usually solved by providing a good hash function with a uniform distribution.

When the HashMap internal array is filled (more on that in the next question), it is automatically resized to be twice as large. This operation infers rehashing (rebuilding of internal data structures), which is costly, so you should plan the size of your HashMap beforehand.

Q6. What Is the Purpose of the Initial Capacity and Load Factor Parameters of a Hashmap? What Are Their Default Values?

The initialCapacity argument of the HashMap constructor affects the size of the internal data structure of the HashMap , but reasoning about the actual size of a map is a bit tricky. The HashMap ‘s internal data structure is an array with the power-of-two size. So the initialCapacity argument value is increased to the next power-of-two (for instance, if you set it to 10, the actual size of the internal array will be 16).

The load factor of a HashMap is the ratio of the element count divided by the bucket count (i.e. internal array size). For instance, if a 16-bucket HashMap contains 12 elements, its load factor is 12/16 = 0.75. A high load factor means a lot of collisions, which in turn means that the map should be resized to the next power of two. So the loadFactor argument is a maximum value of the load factor of a map. When the map achieves this load factor, it resizes its internal array to the next power-of-two value.

The initialCapacity is 16 by default, and the loadFactor is 0.75 by default, so you could put 12 elements in a HashMap that was instantiated with the default constructor, and it would not resize. The same goes for the HashSet , which is backed by a HashMap instance internally.

Consequently, it is not trivial to come up with initialCapacity that satisfies your needs. This is why the Guava library has Maps.newHashMapWithExpectedSize() and Sets.newHashSetWithExpectedSize() methods that allow you to build a HashMap or a HashSet that can hold the expected number of elements without resizing.

Q7. Describe Special Collections for Enums. What Are the Benefits of Their Implementation Compared to Regular Collections?

EnumSet and EnumMap are special implementations of Set and Map interfaces correspondingly. You should always use these implementations when you’re dealing with enums because they are very efficient.

An EnumSet is just a bit vector with “ones” in the positions corresponding to ordinal values of enums present in the set. To check if an enum value is in the set, the implementation simply has to check if the corresponding bit in the vector is a “one”, which is a very easy operation. Similarly, an EnumMap is an array accessed with enum’s ordinal value as an index. In the case of EnumMap , there is no need to calculate hash codes or resolve collisions.

Q8. What Is the Difference Between Fail-Fast and Fail-Safe Iterators?

Iterators for different collections are either fail-fast or fail-safe, depending on how they react to concurrent modifications. The concurrent modification is not only a modification of collection from another thread but also modification from the same thread but using another iterator or modifying the collection directly.

Fail-fast iterators (those returned by HashMap , ArrayList , and other non-thread-safe collections) iterate over the collection’s internal data structure, and they throw ConcurrentModificationException as soon as they detect a concurrent modification.

Fail-safe iterators (returned by thread-safe collections such as ConcurrentHashMap , CopyOnWriteArrayList ) create a copy of the structure they iterate upon. They guarantee safety from concurrent modifications. Their drawbacks include excessive memory consumption and iteration over possibly out-of-date data in case the collection was modified.

Q9. How Can You Use Comparable and Comparator Interfaces to Sort Collections?

The Comparable interface is an interface for objects that can be compared according to some order. Its single method is compareTo , which operates on two values: the object itself and the argument object of the same type. For instance, Integer , Long , and other numeric types implement this interface. String also implements this interface, and its compareTo method compares strings in lexicographical order.

The Comparable interface allows to sort lists of corresponding objects with the Collections.sort() method and uphold the iteration order in collections that implement SortedSet and SortedMap . If your objects can be sorted using some logic, they should implement the Comparable interface.

The Comparable interface usually is implemented using natural ordering of the elements. For instance, all Integer numbers are ordered from lesser to greater values. But sometimes you may want to implement another kind of ordering, for instance, to sort the numbers in descending order. The Comparator interface can help here.

The class of the objects you want to sort does not need to implement this interface. You simply create an implementing class and define the compare method which receives two objects and decides how to order them. You may then use the instance of this class to override the natural ordering of the Collections.sort() method or SortedSet and SortedMap instances.

As the Comparator interface is a functional interface, you may replace it with a lambda expression, as in the following example. It shows ordering a list using a natural ordering ( Integer ‘s Comparable interface) and using a custom iterator ( Comparator<Integer> interface).

Looking for the ideal Linux distro for running modern Spring apps in the cloud?

Meet Alpaquita Linux : lightweight, secure, and powerful enough to handle heavy workloads.

This distro is specifically designed for running Java apps . It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.

Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:

>> Try Alpaquita Containers now.

Explore the secure, reliable, and high-performance Test Execution Cloud built for scale. Right in your IDE:

Basically, write code that works the way you meant it to.

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.

Get started with Spring Boot and with core Spring, through the Learn Spring course:

Build your API with SPRING - book cover

Guru99

80 Java Collections Interview Questions and Answers (2024)

James Hartman

Java Collections Interview Questions and Answers for Freshers

1) what is framework in java.

A framework is a popular and readymade architecture that contains a set of classes and interfaces.

2) What is the Collection framework in Java?

Collection Framework is a grouping of classes and interfaces that is used to store and manage the objects. It provides various classes like Vector, ArrayList, HashSet, Stack, etc. Java Collection framework can also be used for interfaces like Queue, Set, List, etc.

Java Collections Interview Questions

3) Explain Collections Class

java.util.Collections is a class consists of static methods that operate on collections. It contains polymorphic algorithms to operate on collections, “wrappers”. This class contains methods for algorithms, like binary sorting, search, shuffling, etc.

4) What is the hashCode()?

5) distinguish between arraylist and vector in the java collection framework..

ArrayList Vector
ArrayList is cannot be synchronized. Vector can be is synchronized.
It is not a legacy class. It is a legacy class.
It can increase its size by 50% of the size of the array. It can increase its size by doubling the size of the array.
ArrayList is not thread-safe. Vector is a thread-safe.

6) What is ArrayList in Java?

ArrayList is a data structure that can be stretched to accommodate additional elements within itself and shrink back to a smaller size when elements are removed. It is a very important data structure useful in handling the dynamic behavior of elements.

7) Differentiate between Iterator and ListIterator

The difference between Iterator and ListIterator is:

Iterator ListIterator
The Iterator can traverse the array elements in the forward direction. ListIterator can traverse the array elements in backward as well as forward directions.
It can be used in Queue, List, and Set. It can be used in List.
It can perform only remove operation. It can perform add, remove, and set operation while traversing the collection.

8) What is the difference between Iterator and Enumeration?

The difference between Iterator and Enumeration

Iterator Enumeration
The Iterator can traverse both legacies as well as non-legacy elements. Enumeration can traverse only legacy elements.
The Iterator is fail-fast. Enumeration is not fail-fast.
The Iterator is very slow compare to Enumeration. Enumeration is fast compare to Iterator.
The Iterator can perform remove operation while traversing the collection. The Enumeration can perform only traverse operation on the collection.

9) Define BlockingQueue

BlockingQueue is an interface used in Java that can extend the Queue. It provides concurrency in various queue operations like retrieval, insertion, deletion, etc.

The Queue waits to become non-empty at the time of retrieving any elements. BlockingQueue should not contain null elements. The implementation of this Queue is thread-safe.

The syntax of BlockingQueue is:

10) Explain override equals() method

  • Java Program to Check Prime Number
  • How to Reverse a String in Java using Recursion
  • Palindrome Number Program in Java Using while & for Loop

11) What is the difference between Comparable and Comparator?

The difference between Comparable and Comparator is:

Comparable Comparator
Comparable provides compareTo() method to sort elements in Java. Comparator provides compare() method to sort elements in Java.
Comparable interface is present in java.lang package. Comparator interface is present in java. util package.
The logic of sorting must be in the same class whose object you are going to sort. The logic of sorting should be in a separate class to write different sorting based on different attributes of objects.
The class whose objects you want to sort must implement the comparable interface. Class, whose objects you want to sort, do not need to implement a comparator interface.
It provides single sorting sequences. It provides multiple sorting sequences.
This method can sort the data according to the natural sorting order. This method sorts the data according to the customized sorting order.
It affects the original class. i.e., the actual class is altered. It doesn’t affect the original class, i.e., the actual class is not altered.
Implemented frequently in the API by Calendar, Wrapper classes, Date, and String. It is implemented to sort instances of third-party classes.
All wrapper classes and String class implement the comparable interface. The only implemented classes of Comparator are Collator and RuleBasedColator.

12) Explain equals() with example

Equals() verifies whether the number object is equal to the object, which is passed as an argument or not.

The syntax of the equals() method is:

This method takes two parameters 1) any object, 2) return value. It returns true if the passed argument is not null and is an object of a similar type having the same numeric value.

13) List out benefits of generic collection

The benefits of using the generic collection are:

  • If the programmers are using generic class, they don’t require typecasting.
  • It is type-safe and can be checked at the time of compilation.
  • It provides the stability of the code by detecting bug at the compilation time.

14) Explain the method to convert ArrayList to Array and Array to ArrayList

Programmers can convert an Array to ArrayList using asList() method of Arrays class. It is a static method of Arrays class that accept the List object. The syntax of asList() method is:

Java programmers can convert ArrayList to the List object using syntax:

15) Give example of ArrayList

The Example of reverse ArrayList is:

16) Give example to sort an array in dscending order

The example of sort an array in decending order is:

17) Explain the basic interfaces of the Java collections framework

Java collection framework is a root of the collection hierarchy. It represents a group of objects as its elements. The Java programming language does not provide a direct implementation of such interface.

  • Set: Set is a collection having no duplicate elements. It uses hashtable for storing elements.
  • List: List is an ordered collection that can contain duplicate elements. It enables developers to access any elements from its inbox. The list is like an array having a dynamic length.
  • MAP: It is an object which maps keys to values. It cannot contain duplicate keys. Each key can be mapped to at least one value.

18) What are the features of Java Hashmap?

Features of Java Hashmap are:

  • The values can be stored in a map by forming a key-value pair. The value can be retrieved using the key by passing it to the correct method.
  • If no element exists in the Map, it will throw a ‘NoSuchElementException’.
  • HashMap stores only object references. That is why it is impossible to use primitive data types like double or int. Use wrapper class (like Integer or Double) instead.

java collection problem solving questions

19) What is a Stack?

A stack is a special area of computer’s memory that stores temporary variables created by a function. In stack, variables are declared, stored, and initialized during runtime.

20) What is linked list?

A linked list is a data structure that can store a collection of items. In other words, linked lists can be utilized to store several objects of the same type. Each unit or element of the list is referred as a node. A node in the Linked list has its data and the address of the next node. It is like a chain. Linked Lists are used to create graphs and trees.

Java Collections Interview Questions and Answers for Experienced

21) give example of arraylist.

The example of ArrayList is:

22) Explain linked list supported by Java

Two types of linked list supported by Java are:

  • Singly Linked list: Singly Linked list is a type of data structure. In a singly linked list, each node in the list stores the contents of the node and a reference or pointer to the next node in the list. It does not store any reference or pointer to the previous node.
  • Doubly linked lists: Doubly linked lists are a special type of linked list wherein traversal across the data elements can be done in both directions. This is made possible by having two links in every node, one that links to the next node and another one that connects to the previous node.

23) Explain the methods provided by the Queue interface?

Methods of Java Queue interface are:

Method Description
boolean add(object) Inserts specified element into the Queue. It returns true in case it a success.
boolean offer(object) This method is used to insert the element into the Queue.
Object remove() It retrieves and removes the queue head.
Object poll() It retrieves and removes queue head or return null in case if it is empty.
Object poll() It retrieves and removes queue head or return null in case if it is empty.
Object element() Retrieves the data from the Queue, but does not remove its head.
Object peek() Retrieves the data from the Queue but does not remove its head, or in case, if the Queue is the Queue is empty, it will retrieve null.

24) Mention the methods provided by Stack class

Important methods provided by Stack class are:

  • push(): Push item into the stack.
  • empty (): This method finds that whether the stack is empty or not.
  • pop (): This Java collection framework method removes the object from the stack.
  • search (): This method searches items in the stack.
  • peek (): This Java method looks at the stack object without removing it.

25) Define emptySet() in the Java collections framework

Method emptySet() that returns the empty immutable set whenever programmers try to remove null elements. The set which is returned by emptySet() is serializable. The syntax of this method is:

public static final <T> Set<T> emptySet()

26) Differentiate between Collection and Collections

The difference between Collection and Collections are:

Collection Collections
The collection is an interface. Collections is a class.
It represents a group of objects as a single entity. It defines various utility methods for collection objects.
The collection is the root interface of the Java Collection framework. Collections is a general utility class.
This interface is used to derive the collection data structures. This class contains static methods to manipulate data structure.

27) Define LinkedHashSet in the Java Collection framework?

LinkedHashSet is a subclass of the class called HashSet and implements the set interface. It is a well-ordered version of HashSet that maintains a doubly-linked List across its all elements.

28) What is the difference between failfast and failsafe?

Failfast Failsafe
It does not allow collection modification while iterating. It allows collection modification while iterating.
It can throw ConcurrentModificationException It can’t throw any exception.
It uses the original collection to traverse the elements. It uses an original collection copy to traverse the elements.
There is no requirement of extra memory. There is a requirement of extra memory.

29) List collection views of a map interface

Collection views of map interface are: 1) key set view, 2) value set view, and 3) entry set view.

30) What are the benefits of the Collection Framework in Java?

The benefits of Collection Framework in Java are:

  • Java collection framework offers highly efficient and effective data structures that enhance the accuracy and speed of the program.
  • The program developed with the Java collection framework is easy to maintain.
  • A developer can mix classes with other types that result in increasing the reusability of code.
  • The Java collection framework enables programmers to modify the primitive collection types the way they like.

31) What is a good way to sort the Collection objects in Java?

A good way to sort Java collection objects is using Comparable and Comparator interfaces. A developer can use Collections.sort(), the elements are sorted based on the order mention in compareTo().

32) Explain Vector in Java

The vector is the same as an array. It has components that can be accessed using an index value. Vectors can contain a legacy method that is nor part of the collection framework.

33) What is the difference between Set and Map?

Set Map
Set belongs to package-java.util. The map belongs package- java.util.
It can extend the collection interface. It does not extend the collection interface.
It does not allow duplicate values. It allows duplicate values.
Set can sort only one null value. The map can sort multiple null values.

34) Define dictionary class

The Dictionary class is a Java class that has a capability to store key-value pairs.

35) Define EnumSet

java.util.EnumSet is Set implementation that can be used with enum types. EnumSet having all elements must come from one enum type specified explicitly or implicitly. It is not synchronized, and also null keys are not allowed. EnumSet provides methods like EnumSetof(E first, E… rest), complementOf(EnumSet s), and copyOf(Collection c).

36) What are the two ways to remove duplicates from ArrayList?

Two ways to remove duplicates from ArrayList are:

  • HashSet: Developer can use HashSet to remove the duplicate element from the ArrayList. The drawback is it cannot preserve the insertion order.
  • LinkedHashSet: Developers can also maintain the order of insertion by using LinkedHashSet instead of HashSet.

37) What is IdentityHashMap?

IdentityHashMap is a class that implements Serializable, Clonable interfaces, Map, and extends AbstractMap class. It is designed for the case wherein there is a need of reference-equality semantics.

38) What is WeakHashMap?

WeakHashMap is an implementation of the Java Map. It is used to store weak references to its keys. Sorting using this Map allows a key-value pair is collected as garbage. Its key is not referenced outside WeakHashMap.

39) What are the methods to make collection thread-safe?

The methods to make collection thread safe are:

  • Collections.synchronizedList(list);
  • Collections.synchronizedMap(map);
  • Collections.synchronizedSet(set);

40) Explain UnsupportedOperationException

UnsupportedOperationException is an exception whch is thrown on methods that are not supported by actual collection type.

For example, Developer is making a read-only list using “Collections.unmodifiableList(list)” and calling call(), add() or remove() method. It should clearly throw UnsupportedOperationException.

41) Name the collection classes that gives random element access to its elements

Collection classes that give random element access to its elements are: 1) ArrayList, 2) HashMap, 3) TreeMap, and 4) Hashtable.

42) Explain the difference between Queue and Deque.

Queue Deque
It is called a single-ended Queue It is called a double-ended Queue
Elements in the Queue are added or removed from one end Elements in the Queue are added from either end can be added and removed from the both end
It is less versatile. It is more versatile.

43) Mention the implementing List and Set interface

Class implementing List interface: 1) ArrayList, 2) Vector, and 3) LinkedList.

Class implementing Set interface: 1) HashSet, and 2) TreeSet.

44) Explain the design pattern followed by Iterator

The iterator follows the detail of the iterator design pattern. It provides developer to navigate through the objects collections using a common interface without knowing its implementation.

45) What is the peek() of the Queue interface?

Peek () is a method of queue interface. It retrieves all the elements but does not remove the queue head. In case if the Queue is empty, then this method will return null.

46) What is CopyOnWriteArrayList?

CopyOnWriteArrayList is a variant of ArrayList in which operations like add and set are implemented by creating a copy of the array. It is a thread-safe, and thereby it does not throw ConcurrentModificationException. This ArrayLists permits all the elements, including null.

47) Differentiate between ArrayList and LinkedList

The difference between ArrayList and LinkedList is:

ArrayList LinkedList
It uses a dynamic array. It uses a doubly-linked list.
ArrayList is not preferable for manipulation. LinkedList is preferable for manipulation.
ArrayList provides random access. LinkedList does not provide random access.
ArrayList s stores only objects hence it takes less overhead of memory LinkedList stores object as well as address object; hence, it takes more overhead of memory.

48) Explain the methods of iterator interface

Methods of iterator interface are:

Method Description
public boolean hasNext() It returns true in the iterator has elements; otherwise, it returns false.
public Object next() This method returns the element and moves the pointer to the next value.
public void remove() This Java method can remove the last elements returned by the iterator. Public void remove() is less used.

49) What are the methods of the HashSet class?

Methods of HashSet class are:

Methods Description
This method adds the mention element to this set if it is not already present.
It returns true if the set contains the specified element.
This method removes set elements.
It returns true in the case, the set has no elements.
It remove the specified element from the set.
This method returns a copy of the HashSet instance: the elements themselves are not cloned.
It returns an iterator over the elements in this set.
It returns the number of elements available in the set.

50) What are the methods of Java TreeSet class?

The methods of Java TreeSet class are:

Methods Descriptions
boolean addAll(Collection c) Add all the elements in the specified collection to this set.
boolean contains(Object o) Returns true if the set contains the mention element.
boolean isEmpty() This Java method returns true if this set contains no elements.
boolean remove(Object o) Remove the specified element from the set.
void add(Object o) It adds the specified element to the set.
void clear() This Java method removes all the elements from the set.

51) Explain Linked HashSet

Java LinkedHashSet class is a Linked list and Hash table implementation of the Set interface. It contains unique elements same as a HashSet. Linked HashSet in Java also provides optional set operations that can maintain the order of insertion.

52) What are the important methods used in a linked list?

The important methods used in the linked list are:

Method Description
boolean add( Object o) It is used to append the specified element to the end of the vector.
boolean contains(Object o) It a method that returns true if this list contains the specified element.
void add (int index, Object element) Inserts the element at the specified element in the vector.
void addFirst(Object o) It is used to insert the given element at the beginning.
void addLast(Object o) It is used to append the given element to the end.
Int size() This method can be used to return the total number of elements in a list.
boolean remove(Object o) It can remove the first occurrence of the specified element from this list.
int indexOf(Object element) This Java method returns the index with the first occurrence of the mention element in this list, or -1.
int lastIndexOf(Object element) It is a Java method that returns the index with the last occurrence of the specified element in this list, or -1.

53) List various classes available in sets

Various classes available in sets are: HashSet, TreeSetand, and LinkedHashSet.

54) List methods available in Java Queue interface

  • boolean add(object)
  • boolean offer(object)
  • object remove()
  • object poll()
  • object element()
  • object peek()

55) Differentiate between List and Set.

List Set
An ordered collection of elements An unordered collection of elements
Preserves the insertion order Doesn’t preserves the insertion order
Duplicate values are allowed Duplicate values are not allowed
Any number of null values can be stored Only one null values can be stored
ListIterator can be used to traverse the List in any direction ListIterator cannot be used to traverse a Set
Contains a legacy class called vector Doesn’t contains any legacy class

Java Collections Interview Questions and Answers for 5+ Years Experience

56) explain for each loop with example.

For-Each Loop is another form of for loop used to traverse the array. It reduces the code significantly, and there is no use of the index or rather the counter in the loop.

Exmple of for each loop:

57) Explain diamond operator

Diamond operator enables the compiler to collect the type arguments of generic class. In Java SE, developer can substitute the parameterized constructor with an empty parameter sets (<>) known as diamond operator.

58) Explain randomaccess interface

RandomAccess interface is used by List implementations for the indication that they are supporting fast.

59) Name the collection classes that implement random access interface

Java.util package has classes that can implement random access interface are: CopyOnWriteArrayList, Stack, ArrayList, and Vector.

60) How to join multiple ArrayLists?

The list provides a addall() method multiple ArrayList in Java.

For example, consider two lists 1) areaList and 2) secondAreaList. A developer can join them using addall() like:

areaList.addAll(secondAreaList);

61) Explain deque Interface

Java.util.Deque is Java, an interface that extends Queue interface. It gives support for the insertion and deletion of elements at both the end. This Queue is also called a double-ended queue.

62) Explain Linkedhashmap

LinkedHashMap is the implementation of the Map interface. It can also extends the HashMap class. Therefore, like HashMap, LinkedHashMap enables Java developers to allow one null key and more than one null value.

63) Explain methods to remove elements from ArrayList

The methods to remove elements from ArrayList are:

Method Description
clear() This method removes the elements from ArrayList.
remove(int index) This method of ArrayList can remove the element at a particular position.
remove(Object o) It can remove the first occurrence of the mention element from the ArrayList.
removeAll() It can remove the list of elements that are in a particular collection.
removeIf(Predicate<? super E> filter) This method removes elements that satisfy the mention of a predicate.

64) Explain map. entry In Map

Map.entry is a Java interface of java.util. It has a nested interface in Map. This interface must be qualified by the name of class or interface, which it is a member. Therefore it is qualified as a Map. Entry. It represents a key and value pair that can forms element of a Map.

This method returns a view of the collection. For example, consider cityMap as a map. The developer can use entrySet() to get the set view of map having an element Map.Entry. Programmer can also use getKey() and getValue() of the Map.Entry to get the pair of key and value of the map.

65) Which method is used to sort an array in ascending order?

Java collection framework method, Collections.sort() is used to sort an array in ascending order.

66) How to measure the performance of an ArrayList?

The performance of ArrayList can be measure by:

  • Adding an element: Developer can add an element at the end of ArrayList using add(E e) method. It is O(1). In the worst scenario, it might go to O(n). This can happen if the developer add more elements than the array capacity.
  • Retrieving an element: Developer can access the array index using get(int index). The performance, in this case, can be measure using ArrayList get() is O(1).
  • Removing an element: In case, if the developers are removing element using the remove(int index), then the performance of ArrayList can be calculated using said remove(int index) operation is O(n – index) method.

67) Explain LinkedList class

LinkedList class in Java implements Deque and List using a doubly linked list. There is a private class node in a doubly-linked list which provides its structure. It also has an item variable for holding the value and reference to Node class. This can be used for connecting the next and previous nodes.

68) Give an example of Hashmap

The example of Hashmap is:

69) How to iterate map?

The developer cannot directly iterate map, but, this interface has two methods that gives view set of map. These methods are:

  • Set<Map.Entry<K, V>>entrySet(): It is a method that returns a set having the entries mention in the map. These entries are generally objected, which has type Map. Entry.
  • Set<K>keySet(): This Java method returns a set that having the map key.

70) Explain Treemap in Java

TreeMap is a class that implements the Map interface LinkedHashMap and HashMap. It can also implements the NavigableMap interface and can extends the AbstractMap class.

71) What is the difference between Hashmap and Hashtable?

Hashmap Hashtable
It is not synchronized. It is synchronized.
allows one key as a null value. HashTable does not allow null values.
Iterator is used to traverse HashMap. Either Iterator or Enumerator is used for traversing a HashTable.
It can be used for both HashTable, HashMap and is fail-fast. It can be used with HashTable and is fail-safe.
HashMap perform faster than the HashTable. Hashtable is not much faster as compared to HashMap.

72) Explain the internal working of HashSet in Java

HashSet in Java internally uses HashMap to store elements. It can also store unique values with no duplicate values.

In Java, HashSet developer can have add(E e) method that takes just the element to add as a parameter. It does not accept the key and value pair.

73) Explain Big-O notation with an example

The Big-O notation depicts the performance of an algorithm as the number of elements in ArrayList. A developer can use Big-O notation to choose the collection implementation. It is based on performance, time, and memory.

For example, ArrayList get(index i) is a method to perform a constant-time operation. It does not depend on the total number of elements available in the list. Therefore, the performance in Big-O notation is O(1).

74) Explain the best practices in Java Collection Framework

The best practices in Java Collection Framework are:

  • Choose the correct type of collection depends on the need.
  • Avoid rehashing or resizing by estimating the total number of elements to be stored in collection classes.
  • Write a Java program in terms of interfaces. This will help the developer to change it’s implementation effortlessly in the future.
  • A developer can use Generics for type-safety.
  • Use immutable classes given by the Java Development Kit. Avoid implementation of equals() and hashCode() for custom classes.
  • A programmer should use the Collections utility class for algorithms or to get read-only, synchronized, or empty collections. This will enhance code reusability with low maintainability.

75) Explain various types of queues in Java

There are three types of queues in Java:

  • Priority queue: It is a special type of Queue wherein elements are sorted as per their natural ordering or custom comparator.
  • Circular Queue: It is a type of Queue in which user operations are performed based on the FIFO method. The last element is connected to the first position in order to make a circle.
  • Double-ended Queue: A double-ended queue is an abstract data type that generalizes a queue. The elements in this queue can be added or removed from either head or tail.

76) What is the difference between stack and Queue?

Stack Queue
The working principle of the stack is LIFO. Working principale of queue is FIFO.
One end is used to perform the insertion or deletion of elements. One end is used to perform insertion, and another end is used for the deletion of elements.
It uses one pointer. It uses two pointers in a simple queue.
It does not have any kind of variant. It has variants like priority queue, circular Queue, doubly ended Queue.
It is easy to use. It is not easy to use.

77) What is the difference between array and stack?

The difference between array and stack is:

Array Stack
It is a collection of elements that are identified by the index. It is a collection operation that serve as operations push and pop.
It has a elements of data types which are same. It has a elements of data types which are different.
Elements can be removed or added into the array using random access operation. Elements can be removed or added into a stack using LIFO operation.

78) Define Iterator()

The Iterator() is an interface that provides methods to iterate Collection. Iterator can take the place of Enumeration in Java. It allows the caller to remove elements from the collection. The method provides a generic way for traversal using elements of the collection and implementing iterator design pattern.

79) What are the various ways to iterate over a list?

Java collection Framework programmer can iterate over a list in two ways: 1) Using iterator, and 2) using it for each loop .

80) What are the advantages of the stack?

The advantages of the stack are:

  • It helps you to manage the data in a Last In First Out (LIFO) method, which is not possible with the Linked list and array.
  • When a function is called, the local variables are stored in a stack, and it is automatically destroyed once returned.
  • A stack is used when a variable is not used outside that function.
  • It allows you to control how memory is allocated and deallocated.
  • Stack automatically cleans up the object.
  • Not easily corrupted
  • Variables cannot be resized.

These interview questions will also help in your viva(orals)

TopJavaTutorial

Java coding interview questions – collections.

Interview questions topjavatutorial

This is first part of the coding interview questions. You may refer the complete list here :

Java Coding Interview Questions – Part 1 Java Coding Interview Questions – Part 2 Java Coding Interview Questions – Part 3 Java Coding Interview Questions – Part 4 Java Coding Interview Questions – Part 5 Java Coding Interview Questions – Part 6

1. What happens when you compile and run the below program?

package com.javatutorial.quiz; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Quiz38 {   public static void main(String[] args) {     List<Integer> list = new ArrayList<Integer>();          Integer[] arr = {2,10,3};          list = Arrays.asList(arr);          list.set(0, 3);          System.out.println(list);          list.add(1);          System.out.println(list);   } }  

[3,10,3], followed by exception

Arrays.asList() returns a fixed-size list backed by the specified array. Therefore, the arraylist can't grow. So, when add() is called, an exception is thrown.  

2. What will be output of following program ?

  package com.topjavatutorial; import java.util.ArrayList; import java.util.List; public class ArrayListDemo {   public static void main(String[] args) {     List list = new ArrayList();          list.add(10);     list.add(10);          System.out.print(list.size());          list.remove(new Integer(10));          System.out.print(list.size());   } }  

ArralyList can contain duplicate elements. ArrayList remove() method only removes the first occurrence of a matching element.  

3. What will be the output of following Java quiz on PriorityQueue ?

  package com.topjavatutorial; import java.util.PriorityQueue; public class PriorityQueueExample {   public static void main(String[] args) {     PriorityQueue<String> pQueue = new PriorityQueue<String>();     pQueue.add("Apple");     pQueue.add("Nokia");     pQueue.add("Samsung");     pQueue.add("Apple");          System.out.print(pQueue.poll() + " " + pQueue.poll());     System.out.print(" " + pQueue.peek() + " " + pQueue.poll());   } }  

“Apple Apple Nokia Nokia”

PriorityQueue keeps elements sorted and it can have duplicates. add() and offer() methods both offer same functionality. poll() method removes the first element in queue and returns it, while peek() method returns the first element without removing it.  

4. What will be the result for below program?

  package com.topjavatutorial; public class Student {   int rollNumber;      Student(int n){     rollNumber = n;   } } package com.topjavatutorial; import java.util.HashSet; import java.util.Set; public class HashSetDemo {   public static void main(String[] args) {     Set<Student> students = new HashSet<Student>();          students.add(new Student(1));     students.add(new Student(3));     students.add(new Student(4));     students.add(new Student(1));     students.add(new Student(3));          System.out.println(students.size());   } }  

Since Student doesn't override equals(), there are 5 objects in the HashSet.

5. Predict output of following program :

  package com.topjavatutorial; public class Employee implements Comparable<Employee>{    int id;       String name;      Employee(int id, String name){     this.id = id;     this.name = name;   }   @Override   public int compareTo(Employee emp) {     return this.name.compareTo(emp.name);   }    }

package com.topjavatutorial; import java.util.Comparator; public class EmployeeComparator implements Comparator<Employee>{   @Override   public int compare(Employee emp1, Employee emp2) {          return emp2.id - emp1.id;   } } package com.topjavatutorial; import java.util.TreeSet; public class TreeSetDemo{   public static void main(String[] args) {     TreeSet<Employee> empTreeSet = new TreeSet<Employee>(new EmployeeComparator());          Employee emp1 = new Employee(20, "Clark");     Employee emp2 = new Employee(24, "Bernie");     Employee emp3 = new Employee(3, "Alex");          empTreeSet.add(emp1);     empTreeSet.add(emp2);     empTreeSet.add(emp3);               for(Employee emp : empTreeSet)           System.out.print(emp.name + " ");        } }

Bernie Clark Alex

Comparator takes precedence over Comparable, when both are implemented.  

Java Coding Interview Questions – Collections (Part 2)

You may also like :

Test your Java knowledge : 10 Popular and Tricky Java Puzzles   Best 25 Java articles on the web in 2015 (Worth Reading !!)   March 2016 Magazine : TopJavaTutorial articles   Java 8 Interview Questions   Top 10 Java Collection articles

© 2016 – 2023, https: . All rights reserved. On republishing this post, you must provide link to original post

Share this article :

  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Flipboard (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Pocket (Opens in new window)

Popular Articles you may like :

  • Java 8 Interview Questions
  • RESTful CRUD operations using Jersey and Hibernate
  • Frequently asked Java Programming Interview questions on Strings
  • TopJavaTutorial Articles : August 2016 - Top Java Tutorial September 2, 2016 / 10:23 am #
  • Java Coding Interview Questions - Part 5 - Top Java Tutorial August 28, 2016 / 12:22 am #

java collection problem solving questions

The output for question is not “Apple Apple Nokia Nokia”. The correct answer is “Apple Apple Nokia Samsung”

java collection problem solving questions

The correct answer is “Apple Apple Nokia Nokia”. Please run the program to verify.

The third operation is peek(). It does not remove “Nokia”, but just returns it.

Leave a Reply.. code can be added in <code> </code> tags Cancel reply

Data Science

Future Tech

Certificate Program in

Extended Reality (VR+AR)

Executive Program in

Product Management

In collaboration with

Accelerator Program in

Business Analytics and Data Science

In collaboration with,Hero Vired,Accelerator Program in,Business Analytics and Data Science,Part-time · 10 months,Apply by:,August 27, 2024

Gaming and Esports

In collaboration with,NODWIN GAMING,Certificate Program in,Gaming and Esports,Part-time · 8 months,Apply by:,August 27, 2024

Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

menu

Top Java Collections Interview Questions to Know

DevOps & Cloud Engineering

Are you an experienced Java programmer looking to ace your next job interview? Being knowledgeable of Java Collections is essential in mastering your craft. Here, we provide a comprehensive list of the most essential Java collections interview questions to know before taking that crucial job interview. Understanding these topics will help you confidently answer difficult questions and make a lasting impression on potential employers.

Dive deeper to learn about the most common Java Collections interview questions and how to answer them. 

Basic Java Collections Interview Questions

Java Collection interview can be very difficult to get into, so it’s important to know what you’re getting into. We bring to you the top java collection Interview Questions asked with sample answers that would help demonstrate your knowledge of the industry and the job role. 

Some of the most basic java collection interview questions are as follows:

What is Collection in Java?

In Java, a Collection is a framework that provides classes and interfaces to manage and store groups of objects. It allows you to organize, manipulate, and access these objects easily. Collections offer various data structures like lists, sets, and maps, enabling efficient data management in Java applications. It is very crucial to go through all Java Interview questions for better learning.

What is the difference between Array and Collection in Java?

The main difference between an Array and a Collection is in their nature and features in Java. Arrays are fixed in size and can store elements of the same data type, while Collections are dynamic and can store elements of different data types. Collections offer more convenient methods for adding, removing, and manipulating elements than arrays.

Explain the differences between ArrayList and LinkedList

ArrayList and LinkedList are both Java implementations of the List interface, but they differ in their underlying data structures and performance characteristics. ArrayList uses a dynamic array to store elements, providing fast random access but slower insertion and deletion. LinkedList uses a doubly-linked list, offering quick insertion and deletion but slower random access.

Let’s move to the next java collection interview question.

How does the HashSet ensure the uniqueness of elements?

HashSet ensures the uniqueness of elements by using a hashing mechanism. When an element is added to the HashSet, it calculates its hash code and finds the appropriate bucket to store it. If another element with the same hash code already exists in the bucket, the new element is compared for equality. The new element is not added to maintain uniqueness if they are equal.

What is the purpose of the Comparator interface?

The Comparator interface in Java defines custom comparison logic for objects. It allows sorting collections or arrays of objects based on specific criteria that are not the natural order defined by the objects’ classes. This enables developers to sort data flexibly and customizable, depending on their application’s requirements.

Differentiate between Collection and collections in the context of Java.

In Java, “Collection” (with an uppercase “C”) is an interface that represents a group of objects, providing methods for basic collection operations. On the other hand, “collections” (with a lowercase “c”) refer to the utility class java.util. Collections, provides various static methods to manipulate and operate on collections, like sorting, searching, and creating immutable collections. Java Fundamentals are core to your Java programming skills.

What is an Iterator? What is the default size of the load factor in the hashing-based collection?

An Iterator in Java is an interface that allows you to traverse or iterate through the elements of a collection, such as ArrayList , HashSet, or LinkedList. It provides methods like next(), hasNext(), and remove() to access and manipulate the elements in a collection sequentially.

The default size of the load factor in a hashing-based collection is 0.75. The load factor determines the threshold when the collection should be resized (rehashed) to maintain a balance between the number of elements and buckets in the underlying hash table. A load factor of 0.75 ensures a good balance between performance and memory consumption for most scenarios.

What are different ways to iterate over a list?

There are several ways to iterate over a list in Java. The most common approaches are using a for loop, for-each loop (enhanced for loop), Iterator, and ListIterator. The for loop provides index-based iteration, while the for-each loop and Iterator offer simpler, more concise ways to traverse the list’s elements. ListIterator allows bi-directional iteration with additional features like adding and removing elements during iteration. Choose the method that best suits your specific requirements and coding style.

Java Collections Interview Questions for Experienced

A few java collection interview questions for the experienced level are as follows:

What is BlockingQueue in Java?

BlockingQueue in Java is an interface that extends the Queue interface and provides additional methods to support blocking operations. It represents a thread-safe queue where different threads can add or remove elements concurrently. If the queue is full, the put() method blocks until space becomes available, and if it’s empty, the take() method blocks until an element is available for retrieval. This feature is helpful in implementing producer-consumer scenarios and other multi-threaded applications.

What is the difference between Comparable and Comparator?

In Java, Comparable and Comparator are interfaces used for custom sorting of objects. Comparable is implemented by the class itself to define its natural ordering. Comparator is a separate class that allows sorting objects based on different criteria without modifying their original class.

How to remove duplicates from ArrayList?

To remove duplicates from an ArrayList in Java, you can follow these steps:

  • Create a new empty ArrayList or use the existing one to store unique elements.
  • Traverse the original ArrayList using a loop or Iterator.
  • For each element in the original ArrayList, check if it already exists in the new ArrayList using the contains() method.
  • If the element is not present in the new ArrayList, add it to the new ArrayList using the add() method.
  • After iterating through the original ArrayList, the new ArrayList will contain only unique elements.

What is a stack? Give one of its advantages

A stack is a linear data structure in computer science that follows the Last In, First Out (LIFO) principle. Elements are added and removed from the top, resembling a stack of plates. One of its advantages is its simplicity and efficiency in managing function calls and keeping track of program execution flow during recursion.

What is a priority queue in Java?

In Java, a priority queue implements the Queue interface that stores elements based on their priority. Elements with higher priority are dequeued before elements with lower priority.

What is the difference between Queue and Stack?

The main difference between a Queue & a Stack lies in their order of element removal. In a Queue, elements are removed in the order they were added (FIFO – First In, First Out), whereas, in a Stack, the last element added is removed first (LIFO – Last In, First Out).

What is the hashCode()?

hashCode() is a method in Java used to generate a unique integer value (hash code) for an object. It is used in hash-based data structures like HashMap and HashSet to store and retrieve objects efficiently.

What is Enumset?

EnumSet is a specialized Set implementation in Java that is designed to work exclusively with enum types. It offers memory-efficient and high-performance operations for enum values.

Differentiate between Iterator and Enumeration

Availability Part of the newer Java Collections Framework. Part of the older Java Collections Framework.
Bidirectional Support Supports both forward and backward traversal. Supports only forward traversal.
Removal Support Supports element removal using remove() method. Does not have a built-in removal method.
Fail-Fast Behavior Iterator is fail-fast and throws ConcurrentModificationException if the collection is modified during iteration. Enumeration is not fail-fast and may not throw exceptions if the collection is modified during iteration.

In this guide we have discussed some of the most important and common java collection interview questions with answers. Once you are prepared with these java collection interview questions, you have a greater chance of getting the selected in the interview and crack the offer. 

Herovired’s course on and this guide on Data science and busisness analytics course are great resources for diving into Strategic Management.

  • Explain the difference between ArrayList and LinkedList.
  • What is the purpose of the "final" keyword in Java?
  • Describe the usage of "static" keyword with methods and variables.
  • How does Java handle multiple inheritance? Explain using interfaces.
  • What are the different types of exceptions in Java?

brochureimg

The DevOps Playbook

Simplify deployment with Docker containers.

Streamline development with modern practices.

Enhance efficiency with automated workflows.

Download Ebook

Programs tailored for your success.

java collection problem solving questions

PLACEMENT ASSISTANCE

Part-time · 7 Months

Apply by : 27 August, 2024

Download Brochure

java collection problem solving questions

Part-time · 6 Months

java collection problem solving questions

3 ASSURED INTERVIEWS

Hero Vired

Part-time · 10 months

java collection problem solving questions

INTERNSHIP ASSURANCE

NODWIN GAMING

Part-time · 8 months

Accelerator Program in Business Analytics & Data Science

Integrated Program in Data Science, AI and ML

Accelerator Program in AI and Machine Learning

Advanced Certification Program in Data Science & Analytics

Certificate Program in Full Stack Development with Specialization for Web and Mobile

Certificate Program in DevOps and Cloud Engineering

Certificate Program in Application Development

Certificate Program in Cybersecurity Essentials & Risk Assessment

Integrated Program in Finance and Financial Technologies

Certificate Program in Financial Analysis, Valuation and Risk Management

Certificate Program in Strategic Management and Business Essentials

Executive Program in Product Management

Certificate Program in Product Management

Certificate Program in Technology-enabled Sales

Certificate Program in Gaming & Esports

Certificate Program in Extended Reality (VR+AR)

Professional Diploma in UX Design

© 2024 Hero Vired. All rights reserved

Javatpoint Logo

All Interview

Company interview, technical interview, web interview, php interview, .net interview, java interview, database interview.



In Java, collection interview questions are most asked by the interviewers. Here is the list of the most asked collections interview questions with answers.

Collection Framework is a combination of classes and interface, which is used to store and manipulate the data in the form of objects. It provides various classes such as ArrayList, Vector, Stack, and HashSet, etc. and interfaces such as List, Queue, Set, etc. for this purpose.

Array and Collection are somewhat similar regarding storing the references of objects and manipulating the data, but they differ in many ways. The main differences between the array and Collection are defined below:

Collection framework implements various interfaces, Collection interface and Map interface (java.util.Map) are the mainly used interfaces of Java Collection Framework. List of interfaces of Collection Framework is given below:

Collection (java.util.Collection) is the primary interface, and every collection must implement this interface.

Where <E> represents that this interface is of Generic type

List interface extends the Collection interface, and it is an ordered collection of objects. It contains duplicate elements. It also allows random access of elements.

Set (java.util.Set) interface is a collection which cannot contain duplicate elements. It can only include inherited methods of Collection interface

Queue (java.util.Queue) interface defines queue data structure, which stores the elements in the form FIFO (first in first out).

it is a double-ended-queue. It allows the insertion and removal of elements from both ends. It implants the properties of both Stack and queue so it can perform LIFO (Last in first out) stack and FIFO (first in first out) queue, operations.

A Map (java.util.Map) represents a key, value pair storage of elements. Map interface does not implement the Collection interface. It can only contain a unique key but can have duplicate elements. There are two interfaces which implement Map in java that are Map interface and Sorted Map.

No.ArrayListVector
1) ArrayList is not synchronized.Vector is synchronized.
2) ArrayList is not a legacy class.Vector is a legacy class.
3) ArrayList increases its size by 50% of the array size.Vector increases its size by doubling the array size.
4)ArrayList is not ?thread-safe? as it is not synchronized.Vector list is ?thread-safe? as it?s every method is synchronized.

5) What is the difference between ArrayList and LinkedList?

No.ArrayListLinkedList
1) ArrayList uses a dynamic array. LinkedList uses a doubly linked list.
2) ArrayList is not efficient for manipulation because too much is required. LinkedList is efficient for manipulation.
3) ArrayList is better to store and fetch data. LinkedList is better to manipulate data.
4) ArrayList provides random access. LinkedList does not provide random access.
5) ArrayList takes less memory overhead as it stores only objectLinkedList takes more memory overhead, as it stores the object as well as the address of that object.

6) What is the difference between Iterator and ListIterator?

Iterator traverses the elements in the forward direction only whereas ListIterator traverses the elements into forward and backward direction.

No.IteratorListIterator
1) The Iterator traverses the elements in the forward direction only. ListIterator traverses the elements in backward and forward directions both.
2) The Iterator can be used in List, Set, and Queue. ListIterator can be used in List only.
3) The Iterator can only perform remove operation while traversing the collection. ListIterator can perform ?add,? ?remove,? and ?set? operation while traversing the collection.

7) What is the difference between Iterator and Enumeration?

No.IteratorEnumeration
1) The Iterator can traverse legacy and non-legacy elements. Enumeration can traverse only legacy elements.
2) The Iterator is fail-fast. Enumeration is not fail-fast.
3) The Iterator is slower than Enumeration. Enumeration is faster than Iterator.
4) The Iterator can perform remove operation while traversing the collection. The Enumeration can perform only traverse operation on the collection.

8) What is the difference between List and Set?

The List and Set both extend the collection interface. However, there are some differences between the both which are listed below.

  • The List can contain duplicate elements whereas Set includes unique items.
  • The List is an ordered collection which maintains the insertion order whereas Set is an unordered collection which does not preserve the insertion order.
  • The List interface contains a single legacy class which is Vector class whereas Set interface does not have any legacy class.
  • The List interface can allow n number of null values whereas Set interface only allows a single null value.

9) What is the difference between HashSet and TreeSet?

The HashSet and TreeSet, both classes, implement Set interface. The differences between the both are listed below.

  • HashSet maintains�no order�whereas TreeSet maintains�ascending order.
  • HashSet impended by hash table whereas TreeSet implemented by a Tree structure.
  • HashSet performs faster than TreeSet.
  • HashSet is backed by HashMap whereas TreeSet is backed by TreeMap.

10) What is the difference between Set and Map?

The differences between the Set and Map are given below.

  • Set contains values only whereas Map contains key and values both.
  • Set contains unique values whereas Map can contain unique Keys with duplicate values.
  • Set holds a single number of null value whereas Map can include a single null key with n number of null values.

11) What is the difference between HashSet and HashMap?

The differences between the HashSet and HashMap are listed below.

  • HashSet contains only values whereas HashMap includes the entry (key, value). HashSet can be iterated, but HashMap needs to convert into Set to be iterated.
  • HashSet implements Set interface whereas HashMap implements the Map interface
  • HashSet cannot have any duplicate value whereas HashMap can contain duplicate values with unique keys.
  • HashSet contains the only single number of null value whereas HashMap can hold a single null key with n number of null values.

12) What is the difference between HashMap and TreeMap?

The differences between the HashMap and TreeMap are given below.

  • HashMap maintains�no order, but TreeMap maintains�ascending order.
  • HashMap is implemented by hash table whereas TreeMap is implemented by a Tree structure.
  • HashMap can be sorted by Key or value whereas TreeMap can be sorted by Key.
  • HashMap may contain a null key with multiple null values whereas TreeMap cannot hold a null key but can have multiple null values.

13) What is the difference between HashMap and Hashtable?

No.HashMapHashtable
1) HashMap is not synchronized. Hashtable is synchronized.
2) HashMap can contain one null key and multiple null values. Hashtable cannot contain any null key or null value.
3) HashMap is not ?thread-safe,? so it is useful for non-threaded applications.Hashtable is thread-safe, and it can be shared between various threads.
4) 4) HashMap inherits the AbstractMap class Hashtable inherits the Dictionary class.

14) What is the difference between Collection and Collections?

The differences between the Collection and Collections are given below.

  • The Collection is an interface whereas Collections is a class.
  • The Collection interface provides the standard functionality of data structure to List, Set, and Queue. However, Collections class is to sort and synchronize the collection elements.
  • The Collection interface provides the methods that can be used for data structure whereas Collections class provides the static methods which can be used for various operation on a collection.

15) What is the difference between Comparable and Comparator?

No.ComparableComparator
1) Comparable provides only one sort of sequence. The Comparator provides multiple sorts of sequences.
2) It provides one method named compareTo(). It provides one method named compare().
3) It is found in java.lang package. It is located in java.util package.
4) If we implement the Comparable interface, The actual class is modified. The actual class is not changed.

16) What do you understand by BlockingQueue?

BlockingQueue is an interface which extends the Queue interface. It provides concurrency in the operations like retrieval, insertion, deletion. While retrieval of any element, it waits for the queue to be non-empty. While storing the elements, it waits for the available space. BlockingQueue cannot contain null elements, and implementation of BlockingQueue is thread-safe.

17) What is the advantage of Properties file?

If you change the value in the properties file, you don't need to recompile the java class. So, it makes the application easy to manage. It is used to store information which is to be changed frequently. Consider the following example.

18) What does the hashCode() method?

The hashCode() method returns a hash code value (an integer number).

The hashCode() method returns the same integer number if two keys (by calling equals() method) are identical.

However, it is possible that two hash code numbers can have different or the same keys.

If two objects do not produce an equal result by using the equals() method, then the hashcode() method will provide the different integer result for both the objects.

19) Why we override equals() method?

The equals method is used to check whether two objects are the same or not. It needs to be overridden if we want to check the objects based on the property.

For example, Employee is a class that has 3 data members: id, name, and salary. However, we want to check the equality of employee object by the salary. Then, we need to override the equals() method.

20) How to synchronize List, Set and Map elements?

Yes, Collections class provides methods to make List, Set or Map elements as synchronized:

public static List synchronizedList(List l){}
public static Set synchronizedSet(Set s){}
public static SortedSet synchronizedSortedSet(SortedSet s){}
public static Map synchronizedMap(Map m){}
public static SortedMap synchronizedSortedMap(SortedMap m){}

21) What is the advantage of the generic collection?

There are three main advantages of using the generic collection.

  • If we use the generic class, we don't need typecasting.
  • It is type-safe and checked at compile time.
  • Generic confirms the stability of the code by making it bug detectable at compile time.

22) What is hash-collision in Hashtable and how it is handled in Java?

Two different keys with the same hash value are known as hash-collision. Two separate entries will be kept in a single hash bucket to avoid the collision. There are two ways to avoid hash-collision.

  • Separate Chaining
  • Open Addressing

23) What is the Dictionary class?

The Dictionary class provides the capability to store key-value pairs.

24) What is the default size of load factor in hashing based collection?

The default size of load factor is 0.75 . The default capacity is computed as initial capacity * load factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.

25) What do you understand by fail-fast?

The Iterator in java which immediately throws ConcurrentmodificationException, if any structural modification occurs in, is called as a Fail-fast iterator. Fail-fats iterator does not require any extra space in memory.

26) What is the difference between Array and ArrayList?

The main differences between the Array and ArrayList are given below.

SNArrayArrayList
1The Array is of fixed size, means we cannot resize the array as per need.ArrayList is not of the fixed size we can change the size dynamically.
2Arrays are of the static type.ArrayList is of dynamic size.
3Arrays can store primitive data types as well as objects.ArrayList cannot store the primitive data types it can only store the objects.

27) What is the difference between the length of an Array and size of ArrayList?

The length of an array can be obtained using the property of length whereas ArrayList does not support length property, but we can use size() method to get the number of objects in the list.

Finding the length of the array

Finding the size of the ArrayList

28) How to convert ArrayList to Array and Array to ArrayList?

We can convert an Array to ArrayList by using the asList() method of Arrays class. asList() method is the static method of Arrays class and accepts the List object. Consider the following syntax:

We can convert an ArrayList to Array using toArray() method of the ArrayList class. Consider the following syntax to convert the ArrayList to the List object.

29) How to make Java ArrayList Read-Only?

We can obtain java ArrayList Read-only by calling the Collections.unmodifiableCollection() method. When we define an ArrayList as Read-only then we cannot perform any modification in the collection through �add(), remove() or set() method.

30) How to remove duplicates from ArrayList?

There are two ways to remove duplicates from the ArrayList.

  • Using HashSet: By using HashSet we can remove the duplicate element from the ArrayList, but it will not then preserve the insertion order.
  • Using LinkedHashSet: We can also maintain the insertion order by using LinkedHashSet instead of HashSet.

The Process to remove duplicate elements from ArrayList using the LinkedHashSet:

  • Copy all the elements of ArrayList to LinkedHashSet.
  • Empty the ArrayList using clear() method, which will remove all the elements from the list.
  • Now copy all the elements of LinkedHashset to ArrayList.

31) How to reverse ArrayList?

To reverse an ArrayList, we can use reverse() method of Collections class. Consider the following example.

32) How to sort ArrayList in descending order?

To sort the ArrayList in descending order, we can use the reverseOrder method of Collections class. Consider the following example.

33) How to synchronize ArrayList?

We can synchronize ArrayList in two ways.

  • Using Collections.synchronizedList() method
  • Using CopyOnWriteArrayList<T>

34) When to use ArrayList and LinkedList?

LinkedLists are better to use for the update operations whereas ArrayLists are better to use for the search operations.

You may also like:

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

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence Tutorial

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking Tutorial

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering Tutorial

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

  • Java Course
  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot

Java Exercises – Basic to Advanced Java Practice Programs with Solutions

Looking for Java exercises to test your Java skills, then explore our topic-wise Java practice exercises? Here you will get 25 plus practice problems that help to upscale your Java skills.

As we know Java is one of the most popular languages because of its robust and secure nature. But, programmers often find it difficult to find a platform for Java Practice Online. In this article, we have provided Java Practice Programs. That covers various Java Core Topics that can help users with Java Practice.

So, with ado further take a look at our free Java Exercises to practice and develop your Java programming skills. Our Java programming exercises Practice Questions from all the major topics like loops, object-oriented programming, exception handling, and many more.

Topic Wise Java Exercises List

  • Pattern Programs in Java
  • Array Programs in Java
  • String Programs in Java

Java Practice Problems for Searching Algorithms

Practice problems in java sorting algorithms, more java practice exercises.

Java Exercise

Java Practice Programs

This Java exercise is designed to deepen your understanding and refine your Java coding skills, these programs offer hands-on experience in solving real-world problems, reinforcing key concepts, and mastering Java programming fundamentals. Whether you’re a beginner who looking to build a solid foundation or a professional developer aiming to sharpen your expertise, our Java practice programs provide an invaluable opportunity to sharpen your craft and excel in Java programming language .

By diving into these exercises, you’ll not only reinforce key concepts but also gain the practical experience needed to tackle real-world problems effectively. This hands-on practice is essential for mastering Java fundamentals and advancing your career as a proficient Java developer. To further enhance your skills, consider enrolling in our Java Course . This course offers comprehensive lessons and practical exercises, making it an excellent resource for both beginners and experienced developers.

1. Write Hello World Program in Java

The solution to the Problem is mentioned below:

2. Write a Program in Java to Add two Numbers.

Click here for the solution, 3. write a program to swap two numbers, 4. write a java program to convert integer numbers and binary numbers., 5. write a program to find factorial of a number in java., 6. write a java program to add two complex numbers., 7. write a program to calculate simple interest in java, 8. write a program to print the pascal’s triangle in java, 9. write a program to find sum of fibonacci series number, java exercise on pattern.

Pattern Exercises in Java

10. Write a Program to Print Pyramid Number Pattern in Java.

11. write a java program to print pattern., 12. write a java program to print pattern., 13. java program to print patterns., array exercises in java.

Array Exercises in Java

14. Write a Java Program to Compute the Sum of Array Elements.

15. write a java program to find the largest element in array, 16. write java program to find the tranpose of matrix, 17. java array program for array rotation, 18. java array program to remove duplicate elements from an array, 19. java array program to remove all occurrences of an element in an array, string exercises in java.

Strings Exercises in Java

20. Java program to check whether a string is a Palindrome

21. java string program to check anagram, 22. java string program to reverse a string, 23. java string program to remove leading zeros.

Searching Exercises in Java

24. Write a Java Program for Linear Search.

Time Complexity: O(N) Space Complexity: O(N)

25. Write a Binary Search Program in Java.

Time Complexity: O(logN) Space Complexity: O(N)

Sorting_in_java

26. Java Program for Bubble Sort.

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

27. Write a Program for Insertion Sort in Java.

28. java program for selection sort., 29. java program for merge sort..

Time Complexity: O(N logN) Space Complexity: O(N)

30. Java Program for QuickSort.

Time Complexity: O(N logN) Space Complexity: O(1)

After completing these Java exercises you are a step closer to becoming an advanced Java programmer. We hope these exercises have helped you understand Java better and you can solve beginner to advanced-level questions on Java programming.

Solving these Java programming exercise questions will not only help you master theory concepts but also grasp their practical applications, which is very useful in job interviews.

Java Array Exercise Java String Exercise Java Collection Exercise Click Here – To Practice Java Online please check our Practice Portal.

Java Exercise – FAQ

1. how to do java projects for beginners.

To do Java projects you need to know the fundamentals of Java programming. Then you need to select the desired Java project you want to work on. Plan and execute the code to finish the project. Some beginner-level Java projects include: Reversing a String Number Guessing Game Creating a Calculator Simple Banking Application Basic Android Application

2. Is Java easy for beginners?

As a programming language, Java is considered moderately easy to learn. It is unique from other languages due to its lengthy syntax. As a beginner, you can learn beginner to advanced Java in 6 to 18 months.

3. Why Java is used?

Java provides many advantages and uses, some of which are: Platform-independent Robust and secure Object-oriented Popular & in-demand Vast ecosystem

Please Login to comment...

Similar reads.

  • Java-Arrays
  • java-basics
  • Java-Data Types
  • Java-Functions
  • Java-Library
  • Java-Object Oriented
  • Java-Output
  • Java-Strings
  • Output of Java Program
  • How to Get a Free SSL Certificate
  • Best SSL Certificates Provider in India
  • Elon Musk's xAI releases Grok-2 AI assistant
  • What is OpenAI SearchGPT? How it works and How to Get it?
  • Content Improvement League 2024: From Good To A Great Article

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Welcome to Java! Easy Max Score: 3 Success Rate: 97.04%

Java stdin and stdout i easy java (basic) max score: 5 success rate: 96.83%, java if-else easy java (basic) max score: 10 success rate: 91.38%, java stdin and stdout ii easy java (basic) max score: 10 success rate: 92.80%, java output formatting easy java (basic) max score: 10 success rate: 96.54%, java loops i easy java (basic) max score: 10 success rate: 97.67%, java loops ii easy java (basic) max score: 10 success rate: 97.32%, java datatypes easy java (basic) max score: 10 success rate: 93.71%, java end-of-file easy java (basic) max score: 10 success rate: 97.91%, java static initializer block easy java (basic) max score: 10 success rate: 96.12%, cookie support is required to access hackerrank.

Seems like cookies are disabled on this browser, please enable them to open this website

  • ▼Java Exercises
  • ▼Java Basics
  • Basic Part-I
  • Basic Part-II
  • ▼Java Data Types
  • Java Enum Types
  • ▼Java Control Flow
  • Conditional Statement
  • Recursive Methods
  • ▼Java Math and Numbers
  • ▼Object Oriented Programming
  • Java Constructor
  • Java Static Members
  • Java Nested Classes
  • Java Inheritance
  • Java Abstract Classes
  • Java Interface
  • Java Encapsulation
  • Java Polymorphism
  • Object-Oriented Programming
  • ▼Exception Handling
  • Exception Handling Home
  • ▼Functional Programming
  • Java Lambda expression
  • ▼Multithreading
  • Java Thread
  • Java Multithreading
  • ▼Data Structures
  • ▼Strings and I/O
  • File Input-Output
  • ▼Date and Time
  • ▼Advanced Concepts
  • Java Generic Method
  • ▼Algorithms
  • ▼Regular Expressions
  • Regular Expression Home
  • ▼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 Constructor Exercises [ 10 exercises with solution ]
  • Java Static Members Exercises [ 8 exercises with solution ]
  • Java Nested Classes Exercises [ 10 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 [ 14 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 !

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

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

With thousands of potential questions to account for, preparing for the coding interview can feel like an impossible challenge. Yet with a strategic approach, coding interview prep doesn’t have to take more than a few weeks. Stop drilling endless sets of practice problems, and prepare more efficiently by learning coding interview patterns. This course teaches you the underlying patterns behind common coding interview questions. By learning these essential patterns, you will be able to unpack and answer any problem the right way — just by assessing the problem statement. This approach was created by FAANG hiring managers to help you prepare for the typical rounds of interviews at major tech companies like Apple, Google, Meta, Microsoft, and Amazon. Before long, you will have the skills you need to unlock even the most challenging questions, grok the coding interview, and level up your career with confidence. This course is also available in JavaScript, Python, Go, and C++ — with more coming soon!

Using Big O notation is a foundational skill that will be checked by Java interviewers. Before we jump into some more intensive examples, we’ll first go through some questions that test your knowledge and understanding of Big O notation.

As a refresher, Big O is used to classify algorithms based on how their run-time and space requirements grow with input size.

1: Big O of a Nested Loop with Addition

Problem Statement:

Compute the Big O complexity of the code snippet given below.

Try it first on your own, but check our solution if you get stuck.

Solution Breakdown:

The first for loop on line 7 can be broken down into 3 parts:

  • Initialization
  • Incrementation

Since the initialization (int var = 0) only happens once in the entire program, it takes one unit of time. The comparison ( var < n ) gets executed ( n 3 + 1 ) (\frac n3 + 1) ( 3 n ​ + 1 ) times and the increment runs n 3 \frac n3 3 n ​ ​times.

Similarly, ( int j = 0 ) runs n 3 \frac n3 3 n ​ times, the comparison ( j < n ) runs n 3 ∗ ( n 2 + 1 ) \frac n3 * (\frac n2 + 1) 3 n ​ ∗ ( 2 n ​ + 1 ) , and the increment ( j = j + 2 ) gets executed n 2 \frac n2 2 n ​ times for each iteration of the outer loop, so it runs:

n 3 ∗ n 2 = n 2 6 \frac n3 * \frac n2 = \frac {n^2}6 3 n ​ ∗ 2 n ​ = 6 n 2 ​

Below is the line-by-line calculation of time complexity:

java collection problem solving questions

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.

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

Monday, July 1, 2024

  • Top 50 Java Programs from Coding Interviews

Big O Notation cheat sheet

  • 50+ Data Structure and Algorithms Interview Questions
  • 20+ Basic Algorithms Questions from Interviews
  • 20 System Design Interview Questions 
  • How to Crack System Design Interview [The Ultimate Guide]
  • 10 Dynamic Programming Interview Questions
  • 10 Matrix based Coding Problems for Interviews
  • 100+ System Design Interview Questions
  • 25 Recursion based Coding Interview Questions and Answers

31 comments :

Nice collection of interview question

Good Programmas

Good collection

Do you know any other books recommended for coding interviews?

I used: "Cracking the Coding Interview" by Gayle Laakmann McDowell "TOP 30 Java Interview Coding Tasks" by Matthew Urban "Elements of Programming Interviews in Java" by Adnan Aziz, Tsung-Hsien Lee, Amit Prakash "Coding Interview Questions" by Narasimha Karumanchi

nice collection of questions. Thank you.

Really helpful ! Thanks !

String palindrome is found with error.unable to view it

Hello @Unknown, can you give more details? you mean you can't see the solution?

Ah got it, the link is incorrect, I'll correct it.

perfect ...thank you,Guys!

Thanks! for help,guys.

Very nice.. But I need a differential and integral problems in java If any one think about it reply me... We'll discuss about it😊😊😊

Nice thank you

It's very much benificial for us

My problem with this type of question is that most of them do not reflect the types of problems you encounter on the job. A good java programmer knows how to perform task needed by the job. A DB centric application will manipulate many data results efficiently. That might mean knowing lists, iterations, or using lombok. A realtime application will be more focused on things like concurrency. I've used Java professionally since it was in beta nad have never had to shift bits.

Hello Bill, interview and real work is always different. It's part of the culture we have. I think asking these kind of question is to check if people have good fundamental knowledge or not. This is important for engineering a solution rather than just coding. For example, if you know about paging, swap memory, virtual memory you will be better equipped to solve memory related problems of Java application. Just my 2 cent.

Can u plzz help me in solving the below pattern-: 55555 54444 54333 54322 54321

@Unknown, I can give you an hint, use two for loop and a combination of system.out.println() and system.print() to print this pattern

@Unknown public static void main(String[] s) { int i=55555; int r=1111; System.out.println(i); for(int j=0;j<4;j++) { i=i-r; System.out.println(i); r=r/10; }

@Unknown public static void main(String []args){ String num = ""; for(int i = 5; i>=1; i--){ num += i; //System.out.print(i); for(int j = 1; j<=i; j++){ System.out.print(i); } if(i != 1){ System.out.print("\n"+num); } } }

what are the modifiers applicable in java main method

5432 is the answer of program

Very helpful this kind of coding to pass in coding test

Num value is 5

*** * ** ** * *** Please slove this program

Reverse String ..... public class Reve { public static void main(String [] args) { String s="hello java"; String s1=" "; for(int i=s.length()-1;i>=0;i--) { s1=s1+s.CharAt(); } System.out.println("Original String : "+s); System.out.println("Reverse String : "+s1); } }

Can you please add Dynamic Programming Interview questions on this list?

1st non Repeating character and Binary Search were asked.

Any newsletter would you recommend for coding interview preparation?

Post a Comment

Preparing for java and spring boot interview.

  • Join My Newsletter .. Its FREE
  • Everything Bundle (Java + Spring Boot + SQL Interview) for a discount
  • Grokking the Java Interview
  • Grokking the Spring Boot Interview
  • Spring Framework Practice Questions
  • Grokking the SQL Interview
  • Grokking the Java Interview Part 2
  • Grokking the Java SE 17 Developer Certification (1Z0-829 Exam)
  • Spring Professional Certification Practice Test
  • Java SE 11 Certification Practice Test
  • Azure Fundamentals AZ-900 Practice Test
  • Java EE Developer Exam Practice Test
  • Java Foundations 1Z0-811 Exam Practice Test
  • AWS Cloud Practitioner CLF-C02 Exam Practice Test
  • Java SE 17 1Z0-829 Exam Practice Test
  • Azure AI-900 Exam Practice Test
  • 1Z0-829 Java Certification Topic wise Practice Test

My Newsletter articles

  • How to grow financially as Software Engineer?
  • Difference between Microservices and Monolithic Architecture
  • What is Rate Limiter? How does it work
  • Difference between @Component vs @Bean annotations in Spring Framework?
  • Top 10 Software Design Concepts Every Developer should know
  • How does SSO Single Sign On Authentication Works?

Search This Blog

Interview Questions

  • core java interview question (183)
  • interview questions (103)
  • data structure and algorithm (91)
  • Coding Interview Question (81)
  • spring interview questions (52)
  • design patterns (47)
  • object oriented programming (38)
  • SQL Interview Questions (36)
  • thread interview questions (30)
  • collections interview questions (26)
  • database interview questions (16)
  • servlet interview questions (15)
  • hibernate interview questions (10)
  • Programming interview question (6)

Java Tutorials

  • date and time tutorial (25)
  • FIX protocol tutorial (16)
  • Java Certification OCPJP SCJP (30)
  • java collection tutorial (93)
  • java IO tutorial (30)
  • Java JSON tutorial (21)
  • Java multithreading Tutorials (63)
  • Java Programming Tutorials (21)
  • Java xml tutorial (16)
  • jsp-servlet (37)
  • online resources (205)

Get New Blog Posts on Your Email

Get new posts by email:.

  • courses (253)
  • database (50)
  • Eclipse (36)
  • JVM Internals (27)
  • JQuery (23)
  • Testing (21)
  • general (15)

Blog Archive

  • ►  August (13)
  • What is the delegating filter proxy in Spring Secu...
  • 5 Ways to Loop or Iterate over ArrayList in Java?
  • How to get the selected radio button on click usin...
  • 10 Example of Hashtable in Java – Java Hashtable T...
  • How to sort a Map by keys in Java 8 - Example Tuto...
  • Top 30 Array Interview Questions and Answers for P...
  • What is WeakHashMap in Java? When to use it? Examp...
  • 17 SQL Query Best Practices Every Developer Should...
  • How to declare and initialize two dimensional Arra...
  • What is lazy loading in Hibernate? Lazy vs Eager l...
  • Difference between @Secured vs @RolesAllowed vs @P...
  • How to reverse an ArrayList in place in Java? Exam...
  • How to Remove Duplicates from Array without Using ...
  • 12 Apache HTTP Server Interview Questions Answers ...
  • 17 Scenario Based Debugging Interview Questions fo...
  • 10 Singleton Pattern Interview Questions in Java -...
  • 14 Multicasting Interview Questions and Answers
  • Top 20 Algorithms Interview Problems for Programme...
  • How HashMap works in Java?
  • Top 12 SQL Query Problems for Coding Interviews (w...
  • 42 Programming Interview Questions for 1 to 3 Year...
  • ►  June (9)
  • ►  May (45)
  • ►  April (53)
  • ►  March (12)
  • ►  February (4)
  • ►  January (60)
  • ►  December (30)
  • ►  November (7)
  • ►  October (13)
  • ►  September (176)
  • ►  August (54)
  • ►  July (50)
  • ►  June (4)
  • ►  May (206)
  • ►  April (136)
  • ►  March (35)
  • ►  February (11)
  • ►  January (11)
  • ►  December (6)
  • ►  November (1)
  • ►  September (1)
  • ►  August (25)
  • ►  July (44)
  • ►  June (33)
  • ►  May (15)
  • ►  April (37)
  • ►  March (7)
  • ►  February (17)
  • ►  January (23)
  • ►  December (69)
  • ►  November (37)
  • ►  October (23)
  • ►  September (46)
  • ►  August (153)
  • ►  July (237)
  • ►  June (2)
  • ►  May (1)
  • ►  April (2)
  • ►  March (6)
  • ►  February (1)
  • ►  January (1)
  • ►  December (1)
  • ►  October (1)
  • ►  August (1)
  • ►  June (1)
  • ►  May (5)
  • ►  April (13)
  • ►  March (5)
  • ►  February (3)
  • ►  November (4)
  • ►  July (2)
  • ►  April (1)
  • ►  July (1)
  • Privacy Policy
  • Terms and Conditions

java collection problem solving questions

Javarevisited Newsletter

java collection problem solving questions

12 Multithreading Interview Questions for Java Developers

12 multithreading and concurrency interview questions with answers for java programmers.

java collection problem solving questions

Hello guys, Multithreading is an important feature of the Java programming language, which means threads are also an important part of any Java interview.

It's true and in fact, at beginners and freshers, level multithreading interview questions in Java are one of the most difficult to answer.

One reason for interview questions related to multithreading and concurrency being difficult is c onfusion around how multiple threads work together and the second is threads are genuinely a complicated topic to understand and use correctly. Mostly thread interview questions check Java programmer's knowledge on Java Thread API, Java concurrency API, issues related to multi-threading like a race condition, thread-safety, and deadlock. Some time multithreading and concurrency interview question also focus on parallel design patterns like solving the producer-consumer problem , implementing work steal pattern , or solving dining philosopher problem in Java .

This is especially true while interviewing experienced Java developers with 4 to 6 years of experience.

In the past few posts, I have shared popular Java interview questions like,, How ConcurrentHashMap work in Java? Why String is Immutable , why wait() and notify() is called from synchronized context , and difference between List, List<Object> and In this article, I will share popular multithreading questions from interviews.

You will learn about multithreading and concurrency questions asked in various interviews like on telephonic or face-to-face interviews, on written tests, to both experienced and senior Java developers, and some tips to answer them correctly. Btw, if you are a complete beginner to Java threads, I strongly suggest you join a hands-on multithreading course like  Multithreading and Parallel Computing in Java  from Udemy. It's a great course to learn thread basics It's also very affordable and you can get in just $10on Udemy sales.

12 Java Multithreading Interview Questions and Answers

As I said, in this Java article, not only,  I will share some of the most commonly asked thread interview questions at the freshers and beginners level, like up to 2 to 4 years of experience, and some tips and tricks to answer them correctly. By the way, these thread interview questions are equally useful for senior Java developers or guys with some Java experience in hand.

I have tried to share answers to these interview questions on the thread as well but I suggest you do some research and learn the topic well to answer any follow-up questions, which comes due to your response to these thread questions in Java . Anyway here is my collection of Java thread interview questions and how to answer them in Java :

1. What is the difference between the start and run method in Java Thread?

This thread interview question is also asked as if the  start() method eventually calls the  run() method then why do you need to call the  start() method, why not call the  run() method directly.

Well, the reason is that because start method creates a new thread and calls the code written inside the run method on a new thread while calling the run method executes that code on the same thread.

2. Can you write code to avoid deadlock in Java where N threads are accessing N shared resources?

Keep reading with a 7-day free trial.

Subscribe to Javarevisited Newsletter to keep reading this post and get 7 days of free access to the full post archives.

IMAGES

  1. Java Problem Solving Tutorial: Left to Right Evaluation

    java collection problem solving questions

  2. Problem Solving Modules in Java

    java collection problem solving questions

  3. Problem solving with streams in Java Collections

    java collection problem solving questions

  4. Problem Solving in Java Part 1-Introduction

    java collection problem solving questions

  5. Problem Solving in Java

    java collection problem solving questions

  6. Problem Solving Using Java

    java collection problem solving questions

COMMENTS

  1. Java Collection Exercises: Boost Java Coding Skills

    Take a look at our Java Collection Exercise that contains Java Collection Practice Problems to practice and to develop your Java Programming skills. Our Java Collection Practice Exercise will cover all the topics from Basic to Advanced, from ArrayList to Priority Queue. So, let's dive in and sharpen our Java Collection skills together!

  2. Java Collection Exercises

    Learn and practice Java collection with exercises, solutions, and examples. Explore different types of collections, methods, and operations.

  3. Top 50+ Java Collections Interview Questions (2024)

    Here, we've covered the 50+ Java Collections Interview Questions and Answers tailored for both Fresher and experienced professionals, which cover everything from basic to advanced Java collection concepts such as navigation collection, WeakHashMap, streams Lambdas, etc. Java Collections Interview Questions.

  4. Java ArrayList Exercises, Practice & Solutions

    Master Java ArrayList with exercises & solutions. Learn dynamic sizing, random access, generics, iteration & more. Boost your Java skills now!

  5. Java HashMap Exercises, Practice & Solutions

    Master HashMap in Java with exercises & solutions. Learn insertion, counting, copying, removal, checking, and more. Boost your Java skills now!.

  6. 40 Java Collections Interview Questions and Answers

    Java Collections Framework is one of the core APIs of java programming language. It's one of the important topics for java interview questions. Here I am listing some important java collections interview questions and answers to help you in the interview. This is directly coming from my 14+ years of experience in Java programming.

  7. Java Collection Programs

    Java Collection Programs - Basic to Advanced. As it cleared from its name itself "Collection" it is a pre-defined collective bunch of classes and Interfaces present in the "Collection Framework" in Java. Their Classes, Interfaces and Methods are frequently used in competitive programming. This article provides a variety of programs on ...

  8. Java Coding Practice

    What kind of Java practice exercises are there? We've prepared a collection of Java exercises that will help you grasp the syntax of Java language and some core programming topics. In addition, you'll find useful links to articles that cover the theory of Java. Enjoy your Java practice online and enhance your theory knowledge here!

  9. Java Collections Interview Questions

    Java Collections is a topic often brought up on technical interviews for Java developers. This article reviews some important questions that are asked most often and may be tricky to get right. 2. Questions. Q1.

  10. 50+ Java Collections Interview Questions for Beginners and ...

    Java Collection and Generic are a very important topic for Java Interviews. They also present some of the hardest questions to a…

  11. 80 Java Collections Interview Questions and Answers (2024)

    Here are Java Collections Interview Questions for fresher as well as experienced candidates to get their dream job.

  12. Java Collections Framework in Advance Java

    Test your Learn Advance Java knowledge with our Java Collections Framework practice problem. Dive into the world of advance-java challenges at CodeChef.

  13. Top Java Coding Interview Questions on Collections

    Get ready for your Java coding interview with this comprehensive guide to the top Java Collections interview questions. Learn how to answer common questions on Java Collections.

  14. 20+ Java Collections Interview Questions and Answers [2024]

    To prepare for java collections interview questions, review core Java concepts thoroughly and practice coding exercises to strengthen your problem-solving skills.

  15. 800+ Java Practice Challenges // Edabit

    Practice Java coding with fun, bite-sized exercises. Earn XP, unlock achievements and level up. It's like Duolingo for learning to code.

  16. Java Collections Interview Questions (2024)

    Java Collections Interview Questions for beginners and professionals with a list of top 20 frequently asked java collection questions with answers with java, .net ...

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

  18. Top 50 Java Programming Interview Questions

    Introduction If you're interviewing for a Java programming role, then your coding skills will probably be tested. Whether you're a beginner in Java or an expert programmer, this article provides some common Java interview questions and answers to help you prepare.

  19. Java Exercises

    Enhance Java Skills with this Java exercises with detailed solutions for programming proficiency. This Java practice programs ranging from basic to advanced levels questions.

  20. Solve Java

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

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

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

  23. Top 50 Java Programs from Coding Interviews

    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.

  24. Java Interview Questions for Freshers

    Practice this 150 Java MCQs with detailed explanations and prepare yourself for fresher interviews in Java.

  25. 12 Multithreading Interview Questions for Java Developers

    Some time multithreading and concurrency interview question also focus on parallel design patterns like solving the producer-consumer problem, implementing work steal pattern, or solving dining philosopher problem in Java. This is especially true while interviewing experienced Java developers with 4 to 6 years of experience.