28
AugWhat is Data Structure in Java & Classification (Tutorial)
In this Java tutorial, we’ll dive deep into the world of data structures and algorithms and explore how they are implemented in Java. We’ll cover arrays, linked lists, stacks, queues, trees, graphs, and many more. Additionally, we’ll look into sorting and searching algorithms, which are essential for solving problems efficiently.
Ready to master Data Structures and Algorithms? Take the first step by enrolling in our Java Full Stack Developer Course to build your expertise and career!
Read More: Top 50 Java Interview Questions and Answers |
What are Data Structures in Java?
A data structure is a specialized format used to store, organize, and manage data efficiently in computer memory. It is a fundamental concept in computer science that enables the effective handling of large and complex datasets. By using the right data structure, developers can perform operations like data retrieval, insertion, deletion, and modification quickly and efficiently. Whether you are building software, designing a database, or working with real-time systems, choosing the appropriate data structure is essential for achieving high performance and scalability.
Read More: What are Data Structures? |
Why Are Data Structures Important in Java?
Data structures are the backbone of efficient and high-performance Java programming. As applications grow in size and complexity, the volume of data they handle also increases significantly. Without a proper way to organize and manage this data, even the most powerful processors can struggle to deliver optimal performance.
In Java, using the right data structures ensures:
- Faster data processing
- Better memory usage
- Cleaner and more maintainable code
- Understanding and implementing the right data structures is essential for building scalable, responsive, and reliable Java applications.
Need for Data Structures in Java
1. Enhanced Processing Speed- As data volumes increase, it's essential to process information quickly. Data structures organize data in a way that enables faster computation, helping the processor work more efficiently and avoid performance bottlenecks.
2. Efficient Data Organization- Data structures allow for the systematic storage and retrieval of data. Whether you're searching, sorting, or modifying data, using the right structure makes operations quicker and more efficient.
3. Optimized Memory Management- Proper use of data structures ensures effective memory allocation and deallocation, which reduces memory wastage and improves overall application performance.
4. Support for Concurrency and Multithreading- Java provides thread-safe data structures like Concurrent Hash Map and Concurrent Linked Queue, which are essential for multi-threaded applications. These structures help manage shared resources without compromising data integrity.
5. Reusability- Once a data structure is implemented, it can be reused across different parts of the application or even in other projects. This promotes modularity and code reuse, saving time and effort.
6. Higher-Level Abstractions- Java’s Collection Framework offers built-in data structures like Lists, Sets, Maps, and Queues, providing developers with ready-to-use, high-level tools to solve common programming problems efficiently.
Read More: Java Collection Framework |
Classification of Data Structures in Java
Primitive data types are the most basic data types provided by a programming language like Java. They are predefined by the language and store simple values of a single type. These types are not objects and hold raw data.
Examples in Java:
- byte
- short
- int
- long
- float
- double
- char
- boolean
Non-Primitive data types are types created by the programmer or derived from primitive types. These data types can store multiple values or a collection of values, and they are used to represent complex objects.
Examples in Java:
- String
- Arrays
- Classes
- Interfaces
- Collections (e.g., List, Map)
Based on the structure and arrangement of data, these data structures are further divided into two categories.
Classification of Non-Primitive Data Structures:
Non-Primitive Data Structures are broadly categorized based on their arrangement and memory allocation into:
A. Linear Data Structures
Definition: Data is organized in a sequential or linear order, where elements are connected one after the other.
Examples:
- Array
- Linked List
- Stack
- Queue
Types of Linear Data Structures Based on Memory Allocation:
Static Data Structures
- Memory Allocation: At compile-time
- Size: Fixed (cannot be changed after compilation)
- Modifiable Data: Yes
- Example: Array
Dynamic Data Structures
- Memory Allocation: At run-time
- Size: Can be changed during execution
- Modifiable Data & Size: Yes
- Examples: Linked List, Stack, Queue
B. Non-Linear Data Structures
Definition: Data is not stored sequentially. Elements can be connected in multiple ways, forming a hierarchy or network.
Examples:
- Tree
- Graph
Types of Linear Data Structures in Java
1. Arrays
An arrayis a data structure used to store the elements of a particular type. For example, an integer array will hold only the value of any integer, but a character array will hold the characters only. The values get stored at contagious memory locations that can be accessed with their index number.
Syntax
dataType arrayName[arraySize];
Example of Array in Java
class Array_Example
{
public static void main (String[] args)
{
// declaring integer array.
int[] arr;
arr = new int[6];
arr[0] = 10;
arr[1] = 40;
arr[2] = 50;
arr[3] = 20;
arr[4] = 60;
arr[5] = 80;
// accessing the array elements
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
}
In this example, an integer array named "arr" of size 6 is declared and initialized with predetermined values, with each element's index denoting a different integer value.
Output
10
40
50
20
60
80
2. ArrayList
ArrayList is a Java class implemented using the List interface. In the Java ArrayList, the size of the array is not fixed. The List interface extends the Collections framework.
Syntax
import java.util.ArrayList;
// Declare an ArrayList of a specific type
ArrayList arrayListName = new ArrayList<>();
Example of ArrayList in Java
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
// Create an ArrayList to store strings
ArrayList names = new ArrayList<>();
// Add elements to the ArrayList
names.add("ScholarHat");
names.add("Sakshi");
names.add("Sourav");
// Print the elements of the ArrayList
System.out.println("ArrayList elements:");
for (String name : names) {
System.out.println(name);
}
// Access elements by index
String first = names.get(0);
System.out.println("First element: " + first);
// Remove an element
names.remove("Sakshi");
// Check if an element exists
if (names.contains("Sakshi")) {
System.out.println("Sakshi is in the list.");
} else {
System.out.println("Sakshi is not in the list.");
}
// Size of the ArrayList
int size = names.size();
System.out.println("Size of the ArrayList: " + size);
}
}
Output
ArrayList elements:
ScholarHat
Sakshi
Sourav
First element: ScholarHat
Sakshi is not in the list.
Size of the ArrayList: 2
Read More: A Deep Dive into C# Interface |
3. Linked Lists
A Linked List is a linear data structure consisting of a sequence of nodes that are randomly stored in memory. Each node contains two parts:
Data – stores the actual value.
Pointer (or reference) – holds the memory address of the next node in the sequence.
Syntax
LinkedListvar = new LinkedList();
Example of Linked Lists in Java
import java.util.*;
public class Main {
public static void main(String args[]) {
// Creating object of class Linked List
LinkedList ll = new LinkedList();
// Adding elements to linked list
ll.add("ScholarHat");
ll.add("Sakshi");
ll.add("Sourav");
ll.add("Pragati");
// Printing the linked list
System.out.println(ll);
}
}
The above code creates a LinkedList named ll, adds some elements to it, and prints the LinkedList.
Output
[ScholarHat, Sakshi, Sourav, Pragati]
Read More: Linked List in Data Structures |
4. Stack
A stack is an ordered list or a container in which insertion and deletion can be done from one end, known as the top of the stack. The last inserted element is available first and is the first one to be deleted. Hence, it is known as Last In, First Out LIFO, or First In, Last Out FILO. Stacks do not have a fixed size, and their size can be increased or decreased depending on the number of elements.
Syntax
Stack var = new Stack(size);
Example of a Stack in Java
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
Stack stack = new Stack<>();
// Push elements onto the stack
stack.push(100);
stack.push(200);
stack.push(300);
// Print the top element of the stack
System.out.println("Top element:"+stack.peek());
// Pop elements from the stack
int poppedElement=stack.pop();
System.out.println("Popped element:"+poppedElement);
// Check if the stack is empty
System.out.println("Is the stack empty? "+stack.isEmpty());
// Get the size of the stack
System.out.println("Stack size:"+stack.size());
System.out.println("Stack elements:");
for (Integer element:stack)
{
System.out.println(element);
}
}
}
The above program in the Java Editor demonstrates the creation of a Stack and its associated operations.
Output
Top element:300
Popped element:300
Is the stack empty? false
Stack size:2
Stack elements:
100
200
Read More: Implementing Stack in Data Structures |
5. Queue
A queue is an ordered list in which insertion is done at one end called REAR and deletion at another end called FRONT. The first inserted element is available first for the operations to be performed and is the first one to be deleted. Hence, it is known as First In First Out, FIFO, or Last In Last Out, LILO.
Syntax
Queue q1 = new LinkedList();
Example of a Queue in Java Compiler
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static void main(String[] args) {
// Implementing Queue
Queue queue = new LinkedList<>();
// Adding Elements in queue
queue.add("Sakshi");
queue.add("Sourav");
queue.add("Jayanti");
queue.add("Pragati");
System.out.println(queue.peek());
// Removing elements from queue
queue.remove();
queue.remove();
System.out.println(queue.peek());
// Returns the total number of elements present in the queue
System.out.println(queue.size());
// Check if the queue is empty
if (queue.isEmpty()) {
System.out.println("The queue is empty");
} else {
System.out.println("The queue is not empty");
}
}
}
In the above code, we created a queue using a linked list. After that, we perform insertion, deletion, and print operations on the queue.
Output
Sakshi
Jayanti
2
The queue is not empty
Types of Non-Linear Data Structures in Java
1. Graph
A graph is a collection of nodes that consist of data and are connected to other nodes of the graph. Formally a Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is denoted by G(V, E). In a graph, each entity is symbolized by a vertex, while edges denote the connections or associations between entities.
Syntax
BaseType obj = new BaseType ();
Example of Graphs in Java
class Graph {
class Edge {
int src, dst; //source and destination
}
// number of vertices and edges
int vertices, edges;
Edge[] edge;
Graph(int vertices, int edges) {
this.vertices = vertices;
this.edges = edges;
// initialize the edge array
edge = new Edge[edges];
for(int i = 0; i < edges; i++) {
edge[i] = new Edge();
}
}
public static void main(String[] args) {
// create an object of Graph class
int noVertices = 5;
int noEdges = 8;
Graph g = new Graph(noVertices, noEdges);
// create graph
g.edge[0].src = 1;
g.edge[0].dst = 2;
g.edge[1].src = 1;
g.edge[1].dst = 3;
g.edge[2].src = 1;
g.edge[2].dst = 4;
g.edge[3].src = 2;
g.edge[3].dst = 4;
g.edge[4].src = 2;
g.edge[4].dst = 5;
g.edge[5].src = 3;
g.edge[5].dst = 4;
g.edge[6].src = 3;
g.edge[6].dst = 5;
g.edge[7].src = 4;
g.edge[7].dst = 5;
for(int i = 0; i < noEdges; i++) {
System.out.println(g.edge[i].src + " - " + g.edge[i].dst);
}
}
}
The above code initializes a graph with a given number of vertices and edges, creates an array of Edge objects, and sets the source and destination vertices for each edge. Finally, it prints out the source and destination vertices for each edge in the graph.
Output
1 - 2
1 - 3
1 - 4
2 - 4
2 - 5
3 - 4
3 - 5
4 - 5
Read More: Graphs in Data Structures - Types of Graphs, Representation & Operations |
2. Tree
A tree is a collection of objects or entities known as nodes connected by edges, and there is a hierarchical relationship between the nodes. The topmost node of the tree is called the root node from which the tree originates, and the nodes below it are called the child nodes.
Example of Trees in Java
class Tree {
int info;
Tree left, right;
Tree(int info, Tree left, Tree right) {
this.info = info;
this.left = left;
this.right = right;
}
public String toString() {
return info + ", Left child: " + left + ", Right child: " + right;
}
public static void main(String[] args) {
Tree tree = new Tree(1,
new Tree(2, new Tree(0, null, null), new Tree(0, null, null)),
new Tree(3, new Tree(0, null, null), null));
System.out.println(tree);
}
}
The above Java code defines a Tree class with an info field representing the node value and left and right fields representing the left and right child nodes, respectively. The toString() method is overridden to provide a string representation of the tree node and its children.
Output
1, Left child: 2, Left child: 0, Left child: null, Right child: null, Right child: 0, Left child: null, Right child: null, Right child: 3, Left child: 0, Left child: null, Right child: null, Right child: null
Read More: Trees in Data Structures - Its Structure, Operations & Applications |
3. HashMap
HashMap in Java is an implementation of the Map interface that stores data as key-value pairs in a hash table. Each key must be unique and have any non-null reference type. Values can be of any type, including null.
Syntax
Map hashMap = new HashMap<>();
Example of HashMap in Java
import java.util.*;
public class HashMapExample {
public static void main(String[] args) {
// Creating HashMap with String keys and Integer values
Map<String, Integer> map = new HashMap<>();
// Inserting entries in the Map
map.put("Sakshi", 100);
map.put("Sourav", 200);
map.put("Jayanti", 300);
// Iterating over Map using for-each loop
for (Map.Entry<String, Integer> entry : map.entrySet())
// Printing key-value pairs
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
In the above code, we created a HashMap named map that maps String keys to integer values. Three key-value pairs are added to the HashMap using the put method. The entrySet method iterates over the map entries. For each entry in the map, it prints the key-value pair using getKey and getValue methods of the Map. Entry interface.
Output
Sourav 200
Sakshi 100
Jayanti 300
Read More: Interface in Java |
4. HashSet
HashSet class in Java implements the Set interface, a collection of unique elements. It stores the elements in the hash table. HashSet does not accept duplicate values. The order of the objects in the HashSet varies based on their hash code.
Example of HashSet in Java
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
// Create a HashSet to store strings
HashSet<String> hashSet = new HashSet<>();
// Adding elements to the HashSet
hashSet.add("Sakshi");
hashSet.add("Sourav");
hashSet.add("ScholarHat");
hashSet.add("Sakshi"); // Adding duplicate element, will be ignored
System.out.println("HashSet: " + hashSet);
// Check if an element exists in the HashSet
String searchElement = "ScholarHat";
if (hashSet.contains(searchElement)) {
System.out.println(searchElement + " is present in the HashSet.");
} else {
System.out.println(searchElement + " is not present in the HashSet.");
}
// Remove an element from the HashSet
hashSet.remove("Sourav");
System.out.println("After removing Sourav, HashSet: " + hashSet);
// Get the size of the HashSet
int size = hashSet.size();
System.out.println("Size of the HashSet: " + size);
}
}
The above example illustrates how HashSet handles unique elements and provides methods for checking containment and removing elements.
Output
HashSet: [Sourav, Sakshi, ScholarHat]
ScholarHat is present in the HashSet.
After removing Sourav, HashSet: [Sakshi, ScholarHat]
Size of the HashSet: 2
5. TreeMap
TreeMap class in Java implements the SortedMap interface, which extends the Map interface. It uses a Red-Black tree to store key-value pairs in sorted order based on the natural order of the keys.
Example of TreeMap in Java
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Map<String, Integer> treeMap = new TreeMap<>();
// Adding elements to the tree map
treeMap.put("Sakshi", 1);
treeMap.put("Sourav", 3);
treeMap.put("Pragati", 2);
// Getting values from the tree map
int valueA = treeMap.get("Sakshi");
System.out.println("Value of Sakshi: " + valueA);
// Removing elements from the tree map
treeMap.remove("Sourav");
for (String key : treeMap.keySet()) {
System.out.println("Key: " + key + ", Value: " + treeMap.get(key));
}
}
}
The above example showcases TreeMap's functionality for maintaining sorted key-value pairs and performing common map operations like adding, retrieving, and removing elements.
Output
Value of Sakshi: 1
Key: Pragati, Value: 2
Key: Sakshi, Value: 1
6. TreeSet
The TreeSet class of the Collections framework in Java implements the SortedSet interface. You cannot insert duplicate values in the HashSet due to the Set interface. It uses a self-balancing binary search tree to store elements in sorted order.
Example of TreeSet in Java
import java.util.*;
class Treeset_Example {
public static void main(String[] args)
{
Set<string>> ts1 = new TreeSet<>();
// Elements are added using add() method
ts1.add("Sakshi");
ts1.add("Sourav");
ts1.add("ScholarHat");
// Duplicates
ts1.add("ScholarHat");
System.out.println(ts1);
}
}
The above code creates a TreeSet named ts1 to store String elements. Strings are added to ts1 using the add() method. The duplicate elements get ignored. Finally, the contents of ts1, having sorted unique elements, are printed.
Output
[Sakshi, ScholarHat, Sourav]
Read More: Java Collections Interview Questions |
- Efficient Data Management-Data structures help organize and store data efficiently, making it easier to access, process, and modify.
- Faster Searching and Sorting-Structures like trees and hash tables allow quick searching, while algorithms applied on structures like arrays and linked lists enable faster sorting.
- Optimized Memory Usage-With dynamic data structures like linked lists, memory can be allocated and deallocated at runtime, avoiding wastage.
- Reusability-Java provides built-in data structures in the Collections Framework (like List, Set, Map), which can be reused across programs.
- Better Code Readability and Maintenance-Using appropriate data structures makes code cleaner, modular, and easier to maintain.
Read More: Java OOPS Concepts: Encapsulation, Abstraction, Inheritance, Polymorphism |
Choosing the Right Data Structure in Java
1. Understand the Requirements. Begin by clearly understanding the needs of your application:
- What type of data will be stored?
- How frequently will the data be accessed or modified?
- Are there any memory or performance constraints?
- What are the expected input sizes and patterns?
2. Analyze the Required Operations Identify the operations you'll frequently perform on the data:
- Searching
- Inserting and deleting
- Sorting
- Updating
- Traversing Knowing the primary operations helps narrow down the most suitable data structure.
3. Consider Time and Space Complexity
- Evaluate the time and space efficiency of each data structure for the required operations.
- Aim for a balance between performance and memory usage.
4. Leverage Java’s Built-in Data Structures
Java offers a rich Collections Framework that includes many commonly used data structures:
- ArrayList, LinkedList
- HashSet, TreeSet
- HashMap, TreeMap
- Queue, Deque, Priority Queue.
These built-in classes are optimized and should be used wherever possible instead of implementing data structures from scratch. 5. Iterative Refinement: Choosing a data structure is rarely a one-time decision. As your understanding of the problem deepens or new features are added, revisit your data structure choices and refine them accordingly.
Summary
This article explored the key skills for mastering Data Structures and Algorithms in Java. From basic concepts like arrays and linked lists to advanced topics such as graphs and dynamic programming, these skills are crucial for efficient problem-solving in Java. Whether you're starting out or enhancing your skills, mastering DSA is essential for career growth in programming. Ready to excel in Data Structures and Algorithms by Scholarhat? Check out the Scholarhat Master Classes and gain hands-on experience with real-world projects. Advance your tech career with Scholarhat's Best DSA Course | Master Data Structures and Algorithms.
Test Your Knowledge of Data Structures and Algorithms in Java!
Q 1: What is the time complexity of accessing an element in an Array in Java?
- (a) O(1)
- (b) O(n)
- (c) O(log n)
- (d) O(n log n)
Q 2: Which of the following is the most appropriate data structure to implement a queue?
- (a) Stack
- (b) Array
- (c) Linked List
- (d) Priority Queue
Q 3: What is the best time complexity of a binary search in a sorted array?
- (a) O(1)
- (b) O(n)
- (c) O(log n)
- (d) O(n log n)
Q 4: Which sorting algorithm has the best average time complexity?
- (a) Bubble Sort
- (b) Quick Sort
- (c) Merge Sort
- (d) Selection Sort
Q 5: In which of the following cases is a HashMap preferred over a TreeMap?
- (a) When ordering of keys is required
- (b) When searching needs to be faster
- (c) When sorting needs to be performed on the keys
- (d) When keys are comparable
FAQs
Take our Java skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.