DSA · December 4, 2026

DSA in Java, Lesson 1: What Are Data Structures and Algorithms?

Part 1 · Foundations · What Are Data Structures and Algorithms?


🎯 Why Do We Need Data Structures and Algorithms?

Picture two libraries with the same 100,000 books. In the first, books are thrown into boxes in the order they arrived. In the second, every book sits on a labelled shelf, sorted by subject and author. Both libraries hold the same books, but finding one takes a few seconds in the second library and a whole afternoon in the first.

The difference is organisation and method. In programming, the way we organise data is called a data structure, and the step-by-step method we use to work on that data is called an algorithm. Data structures and algorithms (DSA) are the two tools that decide whether a program is slow or fast, simple or messy.

In this first lesson you will meet both ideas, run small Java programs that show why they matter, and see the road map for the whole series.

Data structure
🗄️ How the data is organised
shelves, lists, stacks, trees
+
Algorithm
🧭 Steps to work on the data
search, sort, insert, delete
=
A good program
⚡ fast, clear and
able to handle big data

Figure 1: Organised data plus a good method gives a program that is fast and easy to build on.

1️⃣ What Is a Data Structure?

A data structure is a particular way of storing and organising data in the computer so that it can be used efficiently.

You already use data structures without naming them. An array that holds the marks of students is a data structure. So is a list of contacts on your phone, or the stack of plates in a canteen.

Real-life thingData structure it resemblesWhy it fits
Row of lockers numbered 0, 1, 2, …ArrayEach item has a fixed position number
Stack of platesStackThe last plate put on is the first taken off
Queue at a ticket counterQueueThe first person in line is served first
Train of connected coachesLinked listEach coach is joined to the next one
Family treeTreeEach person has parents and children
Map of cities and roadsGraphPlaces connected by routes

2️⃣ What Is an Algorithm?

An algorithm is a finite, step-by-step set of instructions that solves a problem or completes a task. A cooking recipe is a good example: it lists the ingredients (input), the steps in order, and the finished dish (output).

A proper algorithm has these properties:

PropertyMeaningRecipe example
InputZero or more values given to itRice, water, salt
OutputAt least one resultCooked rice
DefinitenessEach step is clear and unambiguous“Boil for 15 minutes”, not “cook for a while”
FinitenessIt stops after a limited number of stepsThe cooking eventually ends
EffectivenessEach step is simple enough to actually doEvery step can be done with a pot and a stove

The same problem can often be solved by different algorithms. Let us add the numbers from 1 to 100 in two ways.

Program 1: Two algorithms for the same problem

public class SumTwoWays {
    public static void main(String[] args) {
        int n = 100;

        // Way 1: add the numbers one by one
        int sum1 = 0;
        int steps1 = 0;
        for (int i = 1; i <= n; i++) {
            sum1 += i;
            steps1++;
        }

        // Way 2: use the formula n(n+1)/2
        int sum2 = n * (n + 1) / 2;
        int steps2 = 1;

        System.out.println("Loop    : sum = " + sum1 + ", steps = " + steps1);
        System.out.println("Formula : sum = " + sum2 + ", steps = " + steps2);
    }
}
🖥️ Output:
Loop    : sum = 5050, steps = 100
Formula : sum = 5050, steps = 1
  • The loop adds 1, 2, 3, … one by one, so it takes 100 steps.
  • The formula n(n+1)/2 gives the same answer in one step.
  • Both are correct, but the second is much faster. Choosing a better algorithm is the heart of DSA.

3️⃣ Data Structures and Algorithms Work Together

A data structure on its own just holds data, and an algorithm on its own has nothing to work on. Together, they solve problems. Here an array (data structure) holds six names and a linear search (algorithm) looks for one of them.

Program 2: An array and a search algorithm

public class ContactSearch {
    public static void main(String[] args) {
        String[] contacts = {"Aarav", "Diya", "Kabir", "Meera", "Rohan", "Sara"};
        String target = "Meera";
        int position = -1;

        for (int i = 0; i < contacts.length; i++) {
            if (contacts[i].equals(target)) {
                position = i;
                break;
            }
        }

        if (position != -1) {
            System.out.println(target + " found at index " + position);
        } else {
            System.out.println(target + " not found");
        }
    }
}
🖥️ Output:
Meera found at index 3
  • contacts is an array: six names stored at positions 0 to 5.
  • The loop checks each position from the start. When contacts[i] equals the target, it saves the index and stops with break.
  • “Meera” sits at index 3, so the program reports index 3. If the loop ended without a match, the answer would stay -1, meaning “not found”.

Trace table for searching “Meera”:

icontacts[i]Equal to “Meera”?Action
0AaravNoContinue
1DiyaNoContinue
2KabirNoContinue
3MeeraYesposition = 3, stop

4️⃣ Why It Matters: Speed

With six names, any method feels instant. The difference appears when the data is big. Below, a sorted array holds one million numbers, and we count how many steps two different search algorithms need to find the very last one.

Program 3: Counting the steps of two search algorithms

public class StepsCounter {
    public static void main(String[] args) {
        int n = 1_000_000;
        int[] data = new int[n];
        for (int i = 0; i < n; i++) {
            data[i] = i * 2;            // sorted: 0, 2, 4, ...
        }
        int key = 1_999_998;            // the last element

        // Algorithm 1: linear search
        int linearSteps = 0;
        for (int i = 0; i < n; i++) {
            linearSteps++;
            if (data[i] == key) {
                break;
            }
        }

        // Algorithm 2: binary search
        int binarySteps = 0;
        int low = 0, high = n - 1;
        while (low <= high) {
            binarySteps++;
            int mid = (low + high) / 2;
            if (data[mid] == key) {
                break;
            } else if (data[mid] < key) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }

        System.out.println("Elements          : " + n);
        System.out.println("Linear search     : " + linearSteps + " steps");
        System.out.println("Binary search     : " + binarySteps + " steps");
    }
}
🖥️ Output:
Elements          : 1000000
Linear search     : 1000000 steps
Binary search     : 20 steps
  • Linear search starts at the beginning and looks at every element until it finds the key, so it needs 1,000,000 steps here.
  • Binary search looks at the middle, throws away half the array each time, and repeats. It needs only 20 steps for the same job.
  • Binary search only works because the data is sorted. How the data is organised changes which algorithms are possible.
Linear search
worst case steps
Binary search
worst case, about
1,000 items1,00010
1,000,000 items1,000,00020
1,000,000,000 items1,000,000,00030

Figure 2: A thousand times more data costs binary search only about 10 more steps, but costs linear search a thousand times more steps.

📌 Remember: A computer is fast, but it is not infinitely fast. When data grows, the choice of algorithm and data structure decides whether a program finishes in a blink or never finishes.

5️⃣ The Basic Operations on Data

Whatever data structure you use, you will mostly do the same few jobs with it:

OperationWhat it doesExample
TraversalVisit every element oncePrint all your tasks
InsertionAdd a new elementAdd a task to the list
DeletionRemove an elementDelete a finished task
SearchingFind an element or its positionFind where a task is stored
SortingArrange elements in an orderPut tasks in alphabetical order

Program 4: Insert, search, delete and traverse

import java.util.ArrayList;

public class TodoOperations {
    public static void main(String[] args) {
        ArrayList<String> tasks = new ArrayList<>();

        // Insert
        tasks.add("Revise arrays");
        tasks.add("Practise loops");
        tasks.add("Read about recursion");
        System.out.println("After inserting : " + tasks);

        // Search
        int index = tasks.indexOf("Practise loops");
        System.out.println("Search result   : found at index " + index);

        // Delete
        tasks.remove("Practise loops");
        System.out.println("After deleting  : " + tasks);

        // Traverse
        System.out.println("Traversal:");
        for (int i = 0; i < tasks.size(); i++) {
            System.out.println("  " + (i + 1) + ". " + tasks.get(i));
        }
    }
}
🖥️ Output:
After inserting : [Revise arrays, Practise loops, Read about recursion]
Search result   : found at index 1
After deleting  : [Revise arrays, Read about recursion]
Traversal:
  1. Revise arrays
  2. Read about recursion
  • We build a list of tasks with ArrayList, a ready-made Java data structure.
  • add inserts three tasks, indexOf searches for one, remove deletes it, and the for loop traverses what is left.
  • Notice that after the deletion, the remaining items shift to fill the gap. How a structure handles that shifting is something we will study in detail.

6️⃣ A Sneak Peek: Stack and Queue

Two everyday structures behave very differently even though both just store items. A stack is last-in, first-out (LIFO). A queue is first-in, first-out (FIFO).

Program 5: A stack of plates and a queue of people

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Queue;

public class PlatesAndQueue {
    public static void main(String[] args) {
        // A stack of plates: the last plate placed is the first one taken
        Deque<String> plates = new ArrayDeque<>();
        plates.push("Plate 1");
        plates.push("Plate 2");
        plates.push("Plate 3");
        System.out.println("Taken from stack : " + plates.pop());
        System.out.println("Taken from stack : " + plates.pop());

        // A queue at a ticket counter: the first person in line is served first
        Queue<String> line = new ArrayDeque<>();
        line.add("Asha");
        line.add("Bilal");
        line.add("Chitra");
        System.out.println("Served from queue: " + line.remove());
        System.out.println("Served from queue: " + line.remove());
    }
}
🖥️ Output:
Taken from stack : Plate 3
Taken from stack : Plate 2
Served from queue: Asha
Served from queue: Bilal
  • Plates 1, 2 and 3 are pushed on the stack. The first pop() returns Plate 3, the one put on last.
  • Asha, Bilal and Chitra join the queue. The first remove() serves Asha, the one who arrived first.
  • Same items, different rules, so different behaviour. Choosing the right structure means choosing the right rules.
Stack (LIFO)
top: out first ⬇
Plate 3
Plate 2
Plate 1
Queue (FIFO)
out first ➜AshaBilalChitra⬅ in last

Figure 3: A stack removes the newest item first. A queue removes the oldest item first.

7️⃣ Types of Data Structures

Data structures are grouped in a few ways. The most common split is into primitive and non-primitive, and non-primitive ones are further split into linear and non-linear.

Data Structures
Primitive
int, float, char, boolean
Non-primitive
Linear
Array, Linked list,
Stack, Queue
Non-linear
Tree, Graph

Figure 4: Primitive types hold a single value. Non-primitive types organise many values.

  • Linear structures keep items in a line, one after another, so each item has at most one item before it and one after it.
  • Non-linear structures connect items in branching ways, like a family tree or a road map.
  • Lesson 2 looks at these groups in detail.

8️⃣ The Road Map of This Series

This series takes you from the basics to trees and graphs, one small lesson at a time, with Java programs that are compiled and run so that every output you see is real.

Part 1 · Foundations
What DSA is, data structure types, time and space complexity, Big-O, Omega and Theta
Part 2 · Arrays and Strings
Memory layout, insertion, deletion, 2-D arrays, strings
Part 3 · Searching and Sorting
Linear and binary search, bubble, selection, insertion, merge and quick sort
Part 4 · Recursion and Backtracking
Recursion, the call stack, classic problems, N-Queens
Part 5 · Linked Lists
Singly, doubly and circular lists
Part 6 · Stacks and Queues
Stack, expression evaluation, queue, circular queue, deque
Part 7 · Trees
Binary trees, traversals, binary search trees, heaps
Part 8 · Graphs and Hashing
Graph basics, BFS, DFS, hashing

Figure 5: The eight parts of the series, from foundations to graphs.

💡 Tip: Type every program yourself instead of copying it. Run it, change a number, and see what happens. That is how data structures start to feel natural.

⚠️ Common Mistakes and Misconceptions

MisconceptionReality
“Data structures and algorithms are only for interviews”They decide how fast and how reliable everyday software is: search boxes, maps, feeds and payments all use them
“A correct program is a good program”A correct program that takes an hour on big data is not good enough. Speed and memory matter as well
“One data structure is best for everything”Each structure is good at some operations and poor at others. You choose by what you need to do most
“Binary search works on any array”It needs the data to be sorted first
“Algorithm and program are the same thing”An algorithm is the idea in steps. A program is that idea written in a language such as Java
“More code means a better solution”The loop in Program 1 is longer than the formula, and slower

❓ Frequently Asked Questions

Q1. Do I need to know Java well before starting?
Basic Java is enough: variables, loops, if, arrays and methods. Where something new appears, such as ArrayList, it is explained when it first shows up.

Q2. Why Java and not another language?
The ideas of DSA are the same in every language. Java is widely taught, has clear syntax, and has ready-made structures you can compare with the ones you build yourself.

Q3. Is an array really a data structure?
Yes. It is the simplest one: items stored one after another with a position number for each.

Q4. How do I compare two algorithms fairly?
By counting how the number of steps grows as the data grows. That is the topic of time complexity, which comes in Lesson 3.

✅ Key Takeaways

  • A data structure is a way of organising data so it can be used efficiently.
  • An algorithm is a finite, clear set of steps that solves a problem.
  • The two work together, and the right pair makes a program fast and simple.
  • The same problem can have several algorithms. Count the steps to compare them.
  • Common operations are traversal, insertion, deletion, searching and sorting.
  • Stacks are last-in first-out. Queues are first-in first-out.
  • Data structures are primitive or non-primitive, and non-primitive ones are linear or non-linear.
🎓 Practice questions: (1) Give three real-life examples of a stack and three of a queue. (2) Write a Java program that finds the largest number in an array of ten numbers and counts how many comparisons it makes. (3) Change ContactSearch to look for a name that is not in the array and check that it prints “not found”. (4) In StepsCounter, change the key to the first element (0). How many steps does each search need now? Why? (5) List the five properties of an algorithm and check each one against your own recipe for making tea.
All 34 lessons in this series (open all DSA lessons)

Part 1 · Foundations

Part 2 · Arrays and Strings

  • Lesson 5: Arrays: Memory Layout, Traversal, Insertion and Deletion (coming soon)
  • Lesson 6: Two-Dimensional Arrays and Matrices (coming soon)
  • Lesson 7: Strings and Character Arrays (coming soon)
  • Lesson 8: Array Practice Problems (coming soon)

Part 3 · Searching and Sorting

  • Lesson 9: Linear Search (coming soon)
  • Lesson 10: Binary Search (coming soon)
  • Lesson 11: Bubble, Selection and Insertion Sort (coming soon)
  • Lesson 12: Merge Sort (coming soon)
  • Lesson 13: Quick Sort (coming soon)
  • Lesson 14: Comparing Sorting Algorithms (coming soon)

Part 4 · Recursion and Backtracking

  • Lesson 15: Recursion Basics and the Call Stack (coming soon)
  • Lesson 16: Classic Recursion Problems (coming soon)
  • Lesson 17: Backtracking: Subsets and N-Queens (coming soon)

Part 5 · Linked Lists

  • Lesson 18: Singly Linked List: Structure and Traversal (coming soon)
  • Lesson 19: Singly Linked List: Insert, Delete and Search (coming soon)
  • Lesson 20: Doubly Linked List (coming soon)
  • Lesson 21: Circular Linked List (coming soon)

Part 6 · Stacks and Queues

  • Lesson 22: Stack (coming soon)
  • Lesson 23: Stack Applications: Expression Evaluation (coming soon)
  • Lesson 24: Queue (coming soon)
  • Lesson 25: Circular Queue and Deque (coming soon)
  • Lesson 26: Priority Queue (coming soon)

Part 7 · Trees

  • Lesson 27: Trees and Binary Trees (coming soon)
  • Lesson 28: Tree Traversals (coming soon)
  • Lesson 29: Binary Search Tree (coming soon)
  • Lesson 30: Heaps and Heap Sort (coming soon)

Part 8 · Graphs and Hashing

  • Lesson 31: Graphs: Basics and Representation (coming soon)
  • Lesson 32: Breadth-First Search (coming soon)
  • Lesson 33: Depth-First Search (coming soon)
  • Lesson 34: Hashing and Hash Tables (coming soon)