Wednesday, October 29, 2025

Insertion Sort Program in Java

In this post we’ll see how to write Insertion sort program in Java. Insertion sort is good for sorting a small set of elements. Out of the three simpler sorting algorithms insertion sort, selection sort and bubble sort, insertion sort is considered a better option in most of the scenarios.

How Insertion sort works

In insertion sort you take one element at a time and the elements on the left side of the current element are considered temporarily sorted for example if you are at 4th index then elements at index 1..3 are sorted among themselves. But that is not yet the final position because any other element may have to be inserted in between these temporarily sorted elements, which means elements have to be shifted right to make place for the insertion of the element that is why the name insertion sort.

In each iteration the elements on the left of the current element are sorted and current element is compared with all the elements on its left, if it is smaller than any of these elements then it has to be inserted at that index and the elements have to be shifted right to make place for it.

For example if you have an array [5, 2, 6, 1] then you will start with 2 (2nd element) and compare it with elements on its left.

  1. In first iteration 2 is compared with 5. Since it is smaller so it has to be inserted in the place of 5 and other elements have to shifted right. Which gives the array as [2, 5, 6, 1] after first iteration.
  2. In second iteration 6 is compared with 5, since 6 is greater than 5 so nothing needs to be done. So array is still [2, 5, 6, 1].
  3. In third iteration 1 is compared with 6, since it is smaller so elements have to be shifted right which makes the array as [2, 5, 6, 6]. Note that there are more elements on the left to be compared so 1 is still not inserted as its final insertion point is still not sure at this point.
    Then 1 is compared with 5, since 1 is smaller so elements have to be shifted right which makes the array as [2, 5, 5, 6].
    Then 1 is compared with 2, since 1 is smaller so elements have to be shifted right which makes the array as [2, 2, 5, 6].
    At this point left most index is reached so we know that 1 is the smallest element so it is inserted at this index making the array as [1, 2, 5, 6].

Insertion Sort Java program

Logic for writing the insertion sort Java program is as follows-

You take one element (starting from the second element) at a time starting from left to right in the outer loop. Assign this element to a temporary variable.

In inner loop, which starts at the same index as the outer loop and moves toward left, you compare the temp variable with all the previous elements (element on the left of the current index element).

This comparison goes on till both of these conditions hold true-

  • Elements on the left side are greater than the element at the current index.
  • Leftmost element is reached.

In each iteration with in the inner loop, you also have to shift elements right by assigning the previous element to the element at the current index with in the inner loop.

public class InsertionSort {
  public static void main(String[] args) {
    int[] intArr = {47, 85, 62, 34, 7, 10, 92, 106, 2, 54};
    int[] sortedArray = insertionSort(intArr);
    System.out.println("Sorted array is- ");
    for(int num : sortedArray){
      System.out.print(num + " ");
    }
  }
    
  private static int[] insertionSort(int[] intArr){
    int temp;
    int j;
    for(int i = 1; i < intArr.length; i++){
      temp = intArr[i];
      j = i;
      while(j > 0 && intArr[j - 1] > temp){
        // shifting elements to right
        intArr[j] = intArr[j - 1];
        --j;
      }
      // insertion of the element
      intArr[j] = temp;
    }
    return intArr;
  }
}

Output

Sorted array is- 
2 7 10 34 47 54 62 85 92 106 

Time and space complexity of Insertion sort

If you have noticed in the program each time, the number of elements that are to be compared, increases in progression; in first iteration only one element has to be compared, in second iteration two elements have to be compared and so on. Which gives us the number of comparison as–

1 + 2 + 3 + ............ + N-1 = N*(N-1)/2

Which makes the Insertion sort time complexity as O(N2).

In the best case scenario, if the array is already sorted or almost sorted the while loop condition will return false making the time complexity as O(N) if it is already sorted or almost O(N) if the data is almost sorted.

Insertion sort is an in place sorting algorithm so apart from the initial array there is no auxiliary space requirement, thus the space complexity of Insertion sort is O(1).

That's all for this topic Insertion Sort Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Shell Sort Program in Java
  2. Quick Sort Program in Java
  3. Fibonacci Series Program in Java
  4. Remove Duplicate Elements From an Array in Java
  5. How to Create Password Protected Zip File in Java

You may also like-

  1. How to Run a Shell Script From Java Program
  2. Reading Delimited File in Java Using Scanner
  3. Converting Enum to String in Java
  4. Java Program to Get All DB Schemas
  5. How HashMap Internally Works in Java
  6. Race Condition in Java Multi-Threading
  7. Creating Custom Exception Class in Java
  8. Introduction to Hadoop Framework

What is In-place Algorithm

An in-place algorithm is an algorithm that doesn’t use any auxiliary space to transform the input. Though theoretically that would mean if you have an array of length n then you should use that n space itself to transform the input array but in reality you will definitely use some variables and index for array and that kind of auxiliary space is allowed for an in-place algorithm.

Examples of in-place algorithm are sorting algorithms like Bubble sort, Selection Sort, Insertion Sort that don’t require any extra space to perform sorting. That is why space complexity for these algorithms is O(1).

Merge sort, Bucket sort are examples of not in-place or out-of-place sorting algorithms.

In-place algorithm example

Let’s try to understand this auxiliary space requirement of in-place algorithm by taking an algorithm to reverse an array by using separate input and output arrays making it a not in-place algorithm.

import java.util.Arrays;

public class ReverseArray {
  public static void main(String[] args) {
    int[] intArr = {47, 85, 47, 34, 7, 10, 0, 106, 2, 54};
    reverseArray(intArr);
  }
    
  static void reverseArray(int[] intArray) {
    int n = intArray.length;
    // Using another array
    int[] tempArray = new int[n];
    for (int i = 0; i < n; i++) { 
      tempArray[n - i - 1] = intArray[i]; 
    } 
    System.out.println("Reversed Array- " + Arrays.toString(tempArray));
  }
}

But the algorithm to reverse an array can very well be written to use the same input array to reverse it. There is no need to use a separate array making it an in-place algorithm.

public class ReverseArray {
  public static void main(String[] args) {
    int[] intArr = {47, 85, 47, 34, 7, 10, 0, 106, 2, 54};
    reverseArray(intArr);
  }
    
  static void reverseArray(int[] intArray) {
    int n = intArray.length;
    for (int i = 0; i < n / 2; i++) {
      int temp = intArray[i];
      intArray[i] = intArray[n - 1 - i];
      intArray[n - 1 - i] = temp;
    }
    System.out.println("Reversed Array- " + Arrays.toString(intArray));
  }
}

That's all for this topic What is In-place Algorithm. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Shell Sort Program in Java
  2. Tree Sort in Java Using Binary Search Tree
  3. Linear Search (Sequential Search) Java Program
  4. Reverse Each Word in a String Java Program
  5. How to Remove Elements From an Array Java Program

You may also like-

  1. Converting String to Enum Type in Java
  2. How to Read File From The Last Line in Java
  3. Java Program to Get Current Date and Time
  4. Running Dos/Windows Commands From Java Program
  5. How to Loop Through a Map in Java
  6. Difference Between Abstract Class And Interface in Java
  7. Angular One-Way Data Binding Using String Interpolation
  8. Changing String Case in Python

Java Program - Breadth First Search (BFS) Traversal For Graph

In this post we'll see how to write a Java program for breadth-first search (BFS) traversal of a graph.

Graph traversal

To traverse a graph, where you try to reach all the connected vertices from the starting vertex, can be done in following ways-

  1. Depth-first search (DFS)
  2. Breadth-first search (BFS)

Breadth-first search

Contrary to DFS traversal, where algorithm works by moving away from the starting point and trying to go deep, BFS traversal works by visiting all adjacent vertices from the start vertex. Once all the adjacent vertices are exhausted then only it goes to the next level so it tries to traverse the whole breadth of the level before moving to the next level.

For example, if we have the following graph and the starting vertex is "A".

Depth First Search (DFS) Traversal of graph

From "A" you have to go to any unvisited vertex, adjacent to "A". Let's say in this case it goes to "B" then you need to visit the next adjacent vertex of current vertex "A", which will be "C" same way "D" and "E". With this order ABCDE the current level is exhausted (you have explored the full breadth of this branch) so you need to go to the next level.

You have to pick the next current vertex from the current level of "BCDE", if it is "B" then the next adjacent vertex from current vertex "B" is "F". Since there is no other adjacent vertex from "B" so you need to pick another vertex from the "BCDE" level. If it is "C" then the next adjacent vertex from current vertex "C" is "G".

That's the way you do the BFS traversal of the given graph getting the order as "ABCDEFGHIJ".

Breadth-First Search Java program

For implementing Breath-First Search graph traversal program in Java, queue data structure is used to store the vertices that are already visited. Graph may have cycles so you need to keep track of visited vertices by having an extra array of all vertices and you mark the vertices which are already visited.

Graph can be represented using adjacency matrix or by using adjacency list, which of these two ways is used to represent the graph has to be taken in account while writing Java program for BFS traversal of the graph.

Note that in this article undirected graph traversal is done.

Refer post Graph Adjacency Representation - Java Program to get better explanation of graph adjacency representation using adjacency matrix or adjacency list.

Process for Breadth-First Search traversal is as given below-

  1. From the current vertex, visit an adjacent vertex which is not yet visited, mark it as visited and add it to the queue.
  2. Keep repeating step 1 while there are still unvisited adjacent vertices from the current vertex. If there is no unvisited adjacent vertex left then remove a vertex from queue and make it the current vertex. Again, start step 1.
  3. Process is done when queue is empty.

Here is the complete BFS traversal Java program when adjacency matrix is used to represent graph.

import java.util.LinkedList;
import java.util.Queue;

public class GraphBFSAM{
  private int numOfVertices;
  private int[][] adjMatrix;
  // to store all the vertex labels
  Vertex[] vertices;
  private int temp = 0;
  
  // Vertex class as nested class
  static class Vertex{
    String label;
    // to track the visited vertices
    boolean visited;
    Vertex(String label){
      this.label = label;
    }
    public String getLabel() {
      return label;
    }
    public void setLabel(String label) {
      this.label = label;
    }
    public boolean isVisited() {
      return visited;
    }
    public void setVisited(boolean visited) {
      this.visited = visited;
    }    
  }
  
  GraphBFSAM(int numOfVertices){
    this.numOfVertices = numOfVertices;
    vertices = new Vertex[numOfVertices];
    adjMatrix = new int[numOfVertices][numOfVertices];
  }
  
  //Method to add all the graph vertices
  public void addVertex(String label) {
    vertices[temp++] = new Vertex(label);
  }
  
  public void addEdge(int source, int destination) {
    if((source < 0 || source > numOfVertices) || (destination < 0 || destination > numOfVertices)) {
      System.out.println("Invalid edge addition");
      return;
    }
    adjMatrix[source][destination] = 1;
    // For undirected graph reverse setting also required
    adjMatrix[destination][source] = 1;
  }
  
  public void printGraph() {
    for(int i = 0; i < adjMatrix.length; i++) {
      for(int j = 0; j < adjMatrix[0].length; j++) {
        System.out.print(adjMatrix[i][j] + "\t");
      }
      System.out.println();
    }
  }
  
  public void bfsTraversal(int startVertex) {
    Queue<Integer> queue = new LinkedList<Integer>();
    queue.add(startVertex);
    vertices[startVertex].setVisited(true);
    while(!queue.isEmpty()) {
      int currentVertex = queue.poll();
      System.out.print(vertices[currentVertex].getLabel() + " ");
          //Keep adding to the queue while there are still adjacent vertices
      for(int i = 0; i < adjMatrix.length; i++) {
        if(adjMatrix[currentVertex][i] == 1 && !vertices[i].isVisited()) {
          queue.add(i);
          vertices[i].setVisited(true);
        }
      }      
    }
  }
  
  public static void main(String[] args) {
    GraphBFSAM graph = new GraphBFSAM(10);
    graph.addVertex("A");
    graph.addVertex("B");
    graph.addVertex("C");
    graph.addVertex("D");
    graph.addVertex("E");
    graph.addVertex("F");
    graph.addVertex("G");
    graph.addVertex("H");
    graph.addVertex("I");
    graph.addVertex("J");
    
    graph.addEdge(0, 1); //A-B
    graph.addEdge(0, 2); //A-C
    graph.addEdge(0, 3); //A-D
    graph.addEdge(0, 4); //A-E
    graph.addEdge(1, 5); //B-F
    graph.addEdge(5, 8); //F-I
    graph.addEdge(2, 6); //C-G
    graph.addEdge(4, 7); //E-H
    graph.addEdge(7, 9); //H-J


    //graph.printGraph();
    graph.bfsTraversal(0);

  }
}

Output

A B C D E F G H I J

Important points about the program

  1. Uses a static inner class Vertex to encapsulate a vertex with fields as label to store the label of the vertex and Boolean field visited to keep track of the vertex which is already visited.
  2. Adjacency matrix is used here to represent a graph.
  3. Array named vertices is used to store the vertices of the graph and mark the vertices which are already visited.

Here is the complete Java program when adjacency list is used to represent the graph.

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;

public class GraphBFSAL {
  private Map<String, List<String>> adjList;
  // To keep track of already visited vertices
  private Set<String> visited;
  
  GraphBFSAL(){
    adjList = new HashMap<>();
    visited = new HashSet<String>();
  }
  
  public void addVertex(String v) {
    adjList.putIfAbsent(v, new ArrayList<String>());
  }
  
  public void addEdge(String source, String destination) {

    if(!adjList.containsKey(source)) {
      addVertex(source);
    }
    if(!adjList.containsKey(destination)) {
      addVertex(destination);
    }
    adjList.get(source).add(destination);
    // Reverse link also required for undirected graph
    //adjList.get(destination).add(source);
  }
  
  // Method to display graph
  public void printGraph() {
    adjList.forEach((k, v) -> {
      System.out.print("Vertex " + k+ " connects to ");
      v.forEach(e -> System.out.print(e + " "));
      System.out.println();
    });
  }
  
  public void bfsTraversal(String startVertex) {
    Queue<String> queue = new LinkedList<String>();
    queue.add(startVertex);
    visited.add(startVertex);
    while(!queue.isEmpty()) {
      String currentVertex = queue.poll();
      System.out.print(currentVertex+ " ");
      for (String s : adjList.getOrDefault(currentVertex, Collections.emptyList())) {
              if (!visited.contains(s)) {
                queue.add(s);
                visited.add(s);
              }
          }
    }
  }
  
  public static void main(String[] args) {
    GraphBFSAL graph = new GraphBFSAL();

    graph.addEdge("A", "B");
    graph.addEdge("A", "C");
    graph.addEdge("A", "D");
    graph.addEdge("A", "E");
    graph.addEdge("B", "F");
    graph.addEdge("F", "I");
    graph.addEdge("C", "G");
    graph.addEdge("E", "H");
    graph.addEdge("H", "J");
    
    //graph.printGraph();
    graph.bfsTraversal("A");
  }

}

Output

A B C D E F G H I J

Important points about the program-

  1. In the Java program Map and List collections are used to represent adjacency list.
  2. A HashSet named visited is used to store the vertices of the graph and mark the vertices which are already visited.

Time and space complexity of BFS graph traversal

If total number of vertices in the graph are V and the total number of edges are E then the time complexity is O(V2) when graph is represented as an adjacency matrix.

In adjacency matrix we have a 2D array of VXV which means while checking for neighbours of any vertex we have to scan the whole row which is O(V) time, meaning O(V2) for V vertices.

With adjacency list only adjacent vertices are stored as a list for each vertex. For each vertex, the algorithm iterates over adjacency list of that vertex. In an adjacency list representation, every edge appears exactly once (directed graph) or twice (undirected graph). Since the total time = time for vertex processing + time for scanning adjacency list for each vertex = O(V) + O(E)

So, the time complexity is O(V + E).

Auxiliary space requirement is O(V) to store visited vertices in an array or set. Queue may also end up storing V vertices (in worst case) so the space requirement is O(V) for the Queue used in the method.

Thus, the total space requirement is O(V) + O(V), discarding the constants the space complexity is O(V).

Note that adjacency list also takes O(V + E) space and adjacency matrix O(V2) space.

That's all for this topic Java Program - Breadth First Search (BFS) Traversal For Graph. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Weighted Graph Adjacency Representation - Java Program
  2. Java Program to Add and Remove in Graph
  3. Binary Tree Traversal Using Breadth First Search Java Program
  4. Linked List Implementation Java Program
  5. Ternary Search Program in Java

You may also like-

  1. Java Program to Get All DB Schemas
  2. Comparing Enum to String in Java
  3. Arrange Non-Negative Integers to Form Largest Number - Java Program
  4. Printing Numbers in Sequence Using Threads Java Program
  5. Association, Aggregation And Composition in Java
  6. Java Map getOrDefault() Method With Examples
  7. Lazy Initialization in Spring Using lazy-init And @Lazy Annotation
  8. Pure and Impure Pipes in Angular

Sunday, October 26, 2025

String Slicing in Python

String in Python is stored as an array so array indexing can be used to access characters of a String, for example str[0] returns first character of the String str. You may have a scenario where you want to access a part of String rather than a single character, in that case you can use string slicing using slice operator in Python.

Python string slicing

Format of String slicing is as follows-

Stringname[start_position: end_position: increment_step]
  • start_position is the index from which the string slicing starts, start_position is included.
  • end_position is the index at which the string slicing ends, end_position is excluded.
  • increment_step indicates the step size. For example if step is given as 2 then every alternate character from start_position is accessed.

All of these parameters are optional, if start_position is not specified then the slicing starts from index 0. If end_position is not specified then the slicing ends at string_length – 1 (last index). If increment_step is not specified then increment step is 1 by default.

Note that, String slicing creates a new string, it does not modify the original string, as strings in Python are immutable.

Python string slicing examples

1- A simple example where substring from index 2..3 is required.

s = "Python String Slicing"
print(s[2: 4: 1])

Output

th

Here slicing is done from index 2 (start_pos) to index 3 (end_pos-1). Step size is 1.

2- If no parameters are specified.

s = "Python String Slicing"
#both are valid
print(s[:])
print(s[: :])

Output

Python String Slicing
Python String Slicing

3- String slicing when step size is greater than one.

s = "Python String Slicing"
print(s[3: 8 : 2])

Output

hnS

Since the step size is 2 so every other character with in the limits of start_pos and end_pos is accessed.

4- Using string slicing in conjunction with other Python string methods. For example if there is a data in dd/mm/yyyy format and you want to access only the month part. In this case you can use index method to specify the start and end positions for slicing.

s = "03/05/2019"
print(s[s.index("/")+1: s.rindex("/") : 1])

Output

05

String slicing with negative indexing

In string in Python you can also use negative indexing. When negative number is used as index, String is accessed backward so -1 refers to the last character, -2 second last and so on.

Python string slice

1- Reversing the string using slicing. By providing increment_step as -1 you can reverse a string.

s = "Hello World"
reversed = s[: :-1]
print(reversed)

Output

dlroW olleH

2- Using negative value as start position and step size is +1.

s = "Hello World"
str = s[-5: :]
print(str)

Output

World

Here step size is +1 so the indices that are accessed are -5, -4, -3, -2, -1

3- If the start index is greater than or equal to the end index and increment step is positive, an empty string is returned.

s = "Python String Slicing"
print("substring is ", s[12: 8 : 1])

4- If value of the end index is greater than the length of the string then subtring will include characters upto string length, rather than raising an error.

s = "Python String Slicing"
print("substring is", s[14: 40 : 1])

Output

substring is Slicing

That's all for this topic String Slicing in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Comparing Two Strings in Python
  2. Python String isdigit() Method
  3. Python Program to Check Whether String is Palindrome or Not
  4. Encapsulation in Python
  5. Local, Nonlocal And Global Variables in Python

You may also like-

  1. pass Statement in Python
  2. Global Keyword in Python With Examples
  3. self in Python
  4. Constructor in Python - __init__() function
  5. How HashMap Internally Works in Java
  6. Creating PDF in Java Using Apache PDFBox
  7. HDFS Federation in Hadoop Framework
  8. Spring MVC Form Example With Bean Validation

Check String Empty or Not in Python

If you need to check if a String is empty or not in Python then you have the following options.

1. Using len() function to check if String is empty

You can check length of String in Python using len() function. If String is of length zero that means it is an empty string. Here note that String with only whitespaces is considered a non-zero length string, if you want to evaluate such string also as empty string then use strip() method to strip spaces before checking the length of the String.

def check_if_empty(string):
  print('length of String', len(string))
  if len(string) == 0:
    print('empty String')

str1 = ""
check_if_empty(str1)
str2 = "   "
check_if_empty(str2)

Output

length of String 0
empty String
length of String 3

As you can see str2 which is a String with whitespaces is not a length zero String so not considered empty. You need to strip whitespaces for such strings.

def check_if_empty(string):
  print('length of String', len(string))
  if len(string.strip()) == 0:
    print('empty String')

str1 = ""
check_if_empty(str1)
str2 = "   "
check_if_empty(str2)

Output

length of String 0
empty String
length of String 3
empty String

2. Using not to check if String is empty

An empty String is considered false in boolean context so using not string you can find whether the String is empty or not. Here note that String with only whitespaces is not considered false so you need to strip whitespaces before testing for such strings.

def check_if_empty(string):
  if not string.strip():
    print('empty String')

str1 = ""
check_if_empty(str1)
str2 = "   "
check_if_empty(str2)

Output

empty String
empty String

3. Using not with str.isspace() method

An empty String is considered false in boolean context and str.isspace() method returns true if there are only whitespace characters in the string. Using str.isspace() method to check for strings having only whitespaces and not keyword to check for empty strings you can create a composite condition to check for empty strings including those strings which have only whitespaces.

def check_if_empty(string):
  if not string or string.isspace():
    print('empty String')

str1 = ""
check_if_empty(str1)
str2 = "   "
check_if_empty(str2)
str3 = "netjs"
check_if_empty(str3)

Output

empty String
empty String

As you can see both str1 and str2 are considered empty strings.

That's all for this topic Check String Empty or Not in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python String join() Method
  2. Getting Substring in Python String
  3. Python continue Statement With Examples
  4. Class And Object in Python
  5. Name Mangling in Python

You may also like-

  1. Interface in Python
  2. Magic Methods in Python With Examples
  3. List Comprehension in Python With Examples
  4. Binary Tree Implementation in Java - Insertion, Traversal And Search
  5. Java Collections Interview Questions And Answers
  6. Difference Between equals() Method And equality Operator == in Java
  7. Using component-scan in Spring to Automatically Discover Bean
  8. Spring Web Reactive Framework - Spring WebFlux Tutorial

Thursday, October 23, 2025

Java Program - Depth First Search (DFS) Traversal For Graph

In this post we'll see how to write a Java program for depth-first search (DFS) traversal of a graph.

Graph traversal

To traverse a graph, where you try to reach all the connected vertices from the starting vertex, can be done in following ways-

  1. Depth-first search (DFS)
  2. Breadth-first search (BFS)

Depth-First Search

DFS traversal tries to traverse all adjacent vertices from the start vertex, it tries to go deep while exploring a branch and backtracks to starting point once it reaches dead end to start exploring another branch.

For example, if we have the following graph and the starting vertex is "A".

Depth First Search (DFS) Traversal of graph

From "A" you have to go to any vertex, adjacent to "A". So, you see there can be multiple DFS traversal orders of a graph based on how adjacent vertex is picked. Let's say in this case it goes to "B" then you need to visit the next adjacent vertex, which will be "F" and then "I". With this order ABFI the current branch reaches a dead end (you have explored the full depth of this branch) so you need to backtrack and then pick the next adjacent vertex from starting point "A" which is "C" and so on. Final DFS traversal order is A B F I C G D E H J.

DFS traversal for graph is similar to Binary tree DFS traversal with one difference, graph may have cycles so you need to keep track of visited vertices by having an extra array of all vertices and you mark the vertices which are already visited.

Depth-First Search Java program

Depth-First Search traversal program can be written using a recursive method or by using an iterative method with a stack to keep track of traversal.

Graph can be represented using adjacency matrix or by using adjacency list, which of these two ways is used to represent the graph has to be taken in account while writing Java program for DFS traversal of the graph. Note that in this article undirected graph traversal is done.

Refer post Graph Adjacency Representation - Java Program to get better explanation of graph adjacency representation using adjacency matrix or adjacency list.

Process for DFS traversal is as given below-

For recursive logic

  1. Start from the starting vertex and mark it as visited.
  2. Recursively visit all the unvisited adjacent vertices. Mark the visited vertices.
  3. Backtrack when no unvisited adjacent vertices left.

For iterative logic

  1. Start from the starting vertex, mark it as visited and push it on the stack
  2. Visit an unvisited adjacent vertex. Mark the vertex as visited and push it on the stack
  3. Keep doing step 2 while there are adjacent vertices in that branch.
  4. When there are no unvisited adjacent vertices, backtrack by popping vertex of the stack and look for adjacent vertex in another branch.

Here is the complete Java program with both recursive and iterative methods when adjacency matrix is used to represent graph.

import java.util.Stack;

public class GraphBFS {
  private int numOfVertices;
  private int[][] adjMatrix;
  // to store all the vertex labels
  Vertex[] vertices;
  private int temp = 0;
  
  // Vertex class as nested class
  static class Vertex{
    String label;
    // to track the visited vertices
    boolean visited;
    Vertex(String label){
      this.label = label;
    }
    public String getLabel() {
      return label;
    }
    public void setLabel(String label) {
      this.label = label;
    }
    public boolean isVisited() {
      return visited;
    }
    public void setVisited(boolean visited) {
      this.visited = visited;
    }    
  }
  
  GraphBFS(int numOfVertices){
    this.numOfVertices = numOfVertices;
    vertices = new GraphBFS.Vertex[numOfVertices];
    adjMatrix = new int[numOfVertices][numOfVertices];
  }
  
  //Method to add all the graph vertices
  public void addVertex(String label) {
    vertices[temp++] = new Vertex(label);
  }
  
  public void addEdge(int source, int destination) {
    if((source < 0 || source > numOfVertices) || (destination < 0 || destination > numOfVertices)) {
      System.out.println("Invalid edge addition");
      return;
    }
    adjMatrix[source][destination] = 1;
    // For undirected graph reverse setting also required
    adjMatrix[destination][source] = 1;
  }
  
  public void printGraph() {
    for(int i = 0; i < adjMatrix.length; i++) {
      for(int j = 0; j < adjMatrix[0].length; j++) {
        System.out.print(adjMatrix[i][j] + "\t");
      }
      System.out.println();
    }
  }
  
  /* Recursive logic start */
  public void dfs(int startVertex) {
    
    System.out.println("DFS Traversal (Recursive): ");
    dfsRecursive(startVertex, vertices);
  }
  
  public void dfsRecursive(int startVertex, Vertex[] vertices) {
    vertices[startVertex].setVisited(true);
    System.out.print(vertices[startVertex].getLabel() + " ");
    for (int i = 0; i < numOfVertices; i++) {
      if (adjMatrix[startVertex][i] == 1 && !vertices[i].isVisited()) {
        dfsRecursive(i, vertices);
      }
    }
  }
  /* Recursive logic End */
  /* Iterative logic Start */
  public void dfsIterative(int startVertex) {
    boolean[] visited = new boolean[numOfVertices];
    Stack<Integer> stack = new Stack<Integer>();
    stack.push(startVertex);
    
    visited[startVertex] = true;
    
    System.out.print(vertices[startVertex].getLabel() + " ");
    while(!stack.isEmpty()) {
      int v = getNextUnvisitedVertex(stack.peek(), visited);
      if(v == -1) {
        stack.pop();
      }else {
        visited[v] = true;
        System.out.print(vertices[v].getLabel() + " ");
        //System.out.println(v);
        stack.push(v);
      }
    }
  }
  
  private int getNextUnvisitedVertex(int v, boolean[] visited) {
    for(int i = 0; i < numOfVertices; i++) {
      if(adjMatrix[v][i] == 1 && visited[i] == false) {
        return i;
      }
    }
    return -1;
  }
  /* Iterative logic End */
  
  public static void main(String[] args) {
    GraphBFS graph = new GraphBFS(10);
    graph.addVertex("A");
    graph.addVertex("B");
    graph.addVertex("C");
    graph.addVertex("D");
    graph.addVertex("E");
    graph.addVertex("F");
    graph.addVertex("G");
    graph.addVertex("H");
    graph.addVertex("I");
    graph.addVertex("J");
    
    graph.addEdge(0, 1); //A-B
    graph.addEdge(0, 2); //A-C
    graph.addEdge(0, 3); //A-D
    graph.addEdge(0, 4); //A-E
    graph.addEdge(1, 5); //B-F
    graph.addEdge(5, 8); //F-I
    graph.addEdge(2, 6); //C-G
    graph.addEdge(4, 7); //E-H
    graph.addEdge(7, 9); //H-J

    //graph.printGraph();
    graph.dfs(0);
    System.out.println("");
    System.out.println("Graph DFS Traversal (Iterative): ");
    graph.dfsIterative(0);

  }
}

Output

DFS Traversal (Recursive): 
A B F I C G D E H J 
Graph DFS Traversal (Iterative): 
A B F I C G D E H J 

Important points about the program

  1. Uses a static inner class Vertex to encapsulate a vertex with fields as label to store the label of the vertex and Boolean field visited to keep track of the vertex which is already visited.
  2. Adjacency matrix is used here to represent a graph.
  3. Array named vertices is used to store the vertices of the graph and mark the vertices which are already visited.
  4. Method named dfsRecursive() shows the recursive logic.
  5. Method named dfsIterative () shows the iterative logic.

Here is the complete Java program with both recursive and iterative methods when adjacency list is used to represent graph.

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;

public class GrapdhDFSAL {

  private Map<String, List<String>> adjList;
  // To keep track of already visited vertices
  private Set<String> visited;
  
  GrapdhDFSAL(){
    adjList = new HashMap<>();
    visited = new HashSet<String>();
  }
  
  public void addVertex(String v) {
    adjList.putIfAbsent(v, new ArrayList<String>());
  }
  
  public void addEdge(String source, String destination) {

    if(!adjList.containsKey(source)) {
      addVertex(source);
    }
    if(!adjList.containsKey(destination)) {
      addVertex(destination);
    }
    adjList.get(source).add(destination);
    // Reverse link also required for undirected graph
    adjList.get(destination).add(source);
  }
  
  // Method to display graph
  public void printGraph() {
    adjList.forEach((k, v) -> {
      System.out.print("Vertex " + k+ " connects to ");
      v.forEach(e -> System.out.print(e + " "));
      System.out.println();
    });
  }
  
  /* Recursive logic start */
  public void dfs(String startVertex) {
    System.out.println("DFS Traversal (Recursive): ");
    dfsRecursive(startVertex);
  }
  
  public void dfsRecursive(String startVertex) {
    visited.add(startVertex);
    
    System.out.print(startVertex + " ");
    for (String s : adjList.getOrDefault(startVertex, Collections.emptyList())) {
      if (!visited.contains(s)) {
        dfsRecursive(s);
      }
    }
  }
  /* Recursive logic end */
  
  /* Iterative logic Start */
  public void dfsIterative(String startVertex) {
    Stack<String> stack = new Stack<String>();
    stack.push(startVertex);
    
    visited.add(startVertex);
    
    System.out.print(startVertex + " ");
    while(!stack.isEmpty()) {
      String v = getNextUnvisitedVertex(stack.peek());
      if(v.isBlank()) {
        stack.pop();
      }else {
        visited.add(v);
        System.out.print(v + " ");
        stack.push(v);
      }
    }
  }
  
  private String getNextUnvisitedVertex(String v) {
    for (String s : adjList.getOrDefault(v, Collections.emptyList())) {
      if (!visited.contains(s)) {
        return s;
      }
    }
    return "";
  }
  /* Iterative logic End */
  public static void main(String[] args) {
    GrapdhDFSAL graph = new GrapdhDFSAL();

    graph.addEdge("A", "B");
    graph.addEdge("A", "C");
    graph.addEdge("A", "D");
    graph.addEdge("A", "E");
    graph.addEdge("B", "F");
    graph.addEdge("F", "I");
    graph.addEdge("C", "G");
    graph.addEdge("E", "H");
    graph.addEdge("H", "J");
    graph.printGraph();
    // Uncomment this to run recursive method
    //System.out.println("Graph DFS Traversal (Recursive): ");
    //graph.dfs("A");
    System.out.println("Graph DFS Traversal (Iterative): ");
    graph.dfsIterative("A");

  }
}

Output

Vertex A connects to B C D E 
Vertex B connects to A F 
Vertex C connects to A G 
Vertex D connects to A 
Vertex E connects to A H 
Vertex F connects to B I 
Vertex G connects to C 
Vertex H connects to E J 
Vertex I connects to F 
Vertex J connects to H 
Graph DFS Traversal (Iterative): 
A B F I C G D E H J 

Important points about the program

  1. In the Java program, Map and List collections are used to represent adjacency list.
  2. A HashSet named visited is used to store the vertices of the graph and mark the vertices which are already visited.
  3. Method named dfsRecursive() shows the recursive logic.
  4. Method named dfsIterative () shows the iterative logic.

Time and space complexity of DFS graph traversal

If total number of vertices in the graph are V and the total number of edges are E then the time complexity is O(V2) when graph is represented as an adjacency matrix.

In adjacency matrix we have a 2D array of VXV which means while checking for neighbours of any vertex we have to scan the whole row which is O(V) meaning O(V2) for V vertices.

With adjacency list, only adjacent vertices are stored as a list for each vertex. For each vertex, the algorithm iterates over adjacency list of that vertex. In an adjacency list representation, every edge appears exactly once (directed graph) or twice (undirected graph).

Since the total time = time for vertex processing + time for scanning adjacency list for each vertex = O(V) + O(E) So, the time complexity is O(V + E).

Auxiliary space requirement is O(V) to store visited vertices in an array or set. In recursive method, call stack may go up to the recursive depth of V in worst case so recursive call space requirement is O(V).

For iterative method, stack may also end up storing V vertices (in worst case) so the space requirement is O(V) for stack used in iterative method. Thus, the total space requirement is O(V) + O(V), discarding the constants the space complexity is O(V).

That's all for this topic Java Program - Depth First Search (DFS) Traversal For Graph. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Weighted Graph Adjacency Representation - Java Program
  2. Java Program to Add and Remove in Graph
  3. Binary Tree Traversal Using Breadth First Search Java Program
  4. Linked List Implementation Java Program
  5. Bucket Sort Program in Java

You may also like-

  1. Compress And Decompress File Using GZIP Format in Java
  2. Convert Numbers to Words Java Program
  3. Java Program - Sieve of Eratosthenes to Find Prime Numbers
  4. Convert HTML to PDF in Java + Openhtmltopdf and PDFBox
  5. How to Sort ArrayList of Custom Objects in Java
  6. Primitive Data Types in Java
  7. Spring JdbcTemplate Insert, Update And Delete Example
  8. Angular Access Control CanActivate Route Guard Example

Friday, October 17, 2025

Java Program to Find The Frequency of Array Elements

In this post we'll see how to write Java program to find the frequency of elements in an array.

For example-

Input: int[] nums = {1,2,2,3,1,4};
Output- 
1 2
2 2
3 1
4 1

Java program for counting the occurrences of each element in an array can be written using the following approaches.

  1. Using nested loops
  2. Using a frequency array
  3. Using HashMap
  4. Using Java Stream API

Java program to find the frequency of elements in an array using nested loops

With this approach you will have an outer loop, traversing the array one element at a time and an inner loop, starting from the next element (j=i+1) and traversing through the whole array to check if the element currently pointed by the outer loop is found again, if yes then increment the occurrence count for that element.

An extra boolean array is needed to mark the elements that are already visited so that the same element is not counted again.

public class FrequencyArray {

  public static void main(String[] args) {
    int[] nums = {1,2,2,3,1,4};
    countOccurrencesNL(nums);
  }
  
  public static void countOccurrencesNL(int[] nums) {
    int len = nums.length;
    boolean[] visited = new boolean[len];
    for(int i = 0; i < len; i++) {
      if(visited[i]) {
        continue;
      }
      int count = 1;
      int n = nums[i];
      for(int j = i + 1; j < len; j++) {
        if(n == nums[j]) {
          // mark as visited so that it is not picked again
          visited[j] = true;
          count++;
        }
      }
      System.out.println(n + " " +count);
    }
  }
}

Output

1 2
2 2
3 1
4 1

Time and space complexity of this approach

Since there are nested loops with each traversing the whole array of size n therefore the time complexity of this approach is O(n2).

One Boolean array of the same size as the array is also needed so the time complexity is O(n).

Java program to find the frequency of elements in an array using frequency array

In order to count the occurrences of element in an array you can create another frequency array. For that the logic is as given below-

  1. Find the maximum element in the given array and create another frequencyArray with a size equal to maxElement + 1.
  2. The index of frequencyArray represents the element of the given array, and the value at that index stores its frequency. For that iterate through the given array and increment the count at the corresponding index in the frequecyArray.

This logic is suitable for an array with positive values and having values with in a limited range.

public class FrequencyArray {

  public static void main(String[] args) {
    int[] nums = {1,2,2,3,1,4};
    int[] freqArray = countOccurrences(nums);
    // iterate the frequency array
    for(int i = 0; i < freqArray.length; i++) {
      if(freqArray[i] != 0)
        System.out.println(i + " " + freqArray[i]);
  }
  
  public static int[] countOccurrences(int[] nums) {
    int max = Integer.MIN_VALUE;
    // Find the max element in the array
    for(int n : nums) {
      max = Math.max(max, n);
    }
    // Create frequency array
    int[] freqArray = new int[max + 1];
    for (int n : nums) {          
      freqArray[n]++;
    }
    return freqArray;
  }
}

Output

1 2
2 2
3 1
4 1

Time and space complexity of this approach

If the max element in the given array is k then in order to display the count for each element, we need three separate iterations as per the logic which means O(n) + O(n) + O(k).

Which can be taken as O(n) if the range is limited.

A frequency array of size k is needed so the space complexity is O(k).

Java program to find the frequency of elements in an array using HashMap

Another way to write a Java program to count the occurrences of each element in an array is to use a HashMap. Logic for this approach is as given below-

  1. Iterate over the array and store array element as key and its frequency as value in the HashMap.
  2. Check if key (array element) already exists in the Map, if yes then increment the value by 1. If not present then add the element as key and value as 1.
import java.util.HashMap;
import java.util.Map;

public class FrequencyArray {

  public static void main(String[] args) {
    int[] nums = {1,2,2,3,1,4};
    countOccurrencesMap(nums);
  }
  
  public static void countOccurrencesMap(int[] nums) {
    Map<Integer, Integer> freqMap = new HashMap<>();
    for(int n : nums) {
      freqMap.put(n, freqMap.getOrDefault(n, 0)+1);
    }
    for(Map.Entry<Integer,Integer> entry : freqMap.entrySet()){
          System.out.println(entry.getKey() + " " + entry.getValue());
    }
  }
}

Output

1 2
2 2
3 1
4 1

Time and space complexity of this approach

There is one iteration of the array to store elements in the HashMap. For each element, the getOrDefault() and put() operations on a HashMap have an average time complexity of O(1). Therefore, the total time complexity of this logic is O(n).

Since HashMap stores only unique elements, so the space complexity is O(k), considering the number of unique elements is k.

Java program to find the frequency of elements in an array using Java Stream API

The Collectors.groupingBy() method in Java Stream API can be used to group element with their repective count. For counting another method Collectors.counting() is used.

boxed() method in Java Stream API is also required to convert primitive int to Integer for stream operations.

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class FrequencyArray {

  public static void main(String[] args) {
    int[] nums = {1,2,2,3,1,4};
    countOccurrencesStream(nums);
  }
  
  public static void countOccurrencesStream(int[] nums) {
    //Map<Integer, Integer> freqMap = new HashMap<>();
    Map<Integer, Long> freqMap = Arrays.stream(nums)
                      .boxed()
                      .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    
    for(Map.Entry<Integer,Long> entry : freqMap.entrySet()){
        System.out.println(entry.getKey() + " " + entry.getValue());
    }
  }
}

Output

1 2
2 2
3 1
4 1

Time and space complexity of this approach

Arrays.stream() traverses the whole array which is O(n), in the same pass boxed() converts int to Integer and grouping is done by incrementing the count in the HashMap or by adding a new element, put() and get() methods in HahsMap are considered O(1). Thus the time complexity of this approach is O(1).

Since HashMap stores only unique elements, so the space complexity is O(k), considering the number of unique elements is k. Worst case is O(n) if all the array elements are unique.

That's all for this topic Java Program to Find The Frequency of Array Elements. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Find The Maximum Element in Each Row of a Matrix Java Program
  2. Array Rotation Java Program
  3. How to Remove Elements From an Array Java Program
  4. Count Number of Words in a String Java Program
  5. Count Number of Times Each Character Appears in a String Java Program

You may also like-

  1. Java Program - Sieve of Eratosthenes to Find Prime Numbers
  2. Writing a File Asynchronously Java Program
  3. Java Program to Detect And Remove Loop in a Linked List
  4. How to Display Time in AM-PM Format in Java
  5. Java Map computeIfPresent() With Examples
  6. Method Overloading in Python
  7. Angular Route Parameters - Setting and Fetching
  8. React Virtual DOM

Thursday, October 16, 2025

Binary Tree Traversal Using Breadth First Search Java Program

In this post we’ll see a Java program to do a Binary tree traversal using breadth first search which is also known as level order traversal of binary tree.

Breadth first search

Contrary to the depth first search where traversal is done by moving to node in the next level, in breadth first search all the nodes with in the same level are visited then only next level is visited.

For depth search Java program refer this post- Binary Tree Traversal Using Depth First Search Java Program

The level order traversal of the binary tree, in the above image will happen in the following order-

  1. Level 0 – 50
  2. Level 1- 30, 70
  3. Level 2- 15, 35, 62, 87
  4. Level 3- 7, 22, 31

Breadth first Java program for a binary tree can be written using both-

Breadth first search Recursive Java program

To write a Java program to recursively do a level order traversal of a binary tree you need to calculate height of the tree and then call method for level order traversal for level 0 to max level of the binary tree.

public void levelOrder(){
  int height = calculateTreeHeight(root);
  for(int i = 0; i < height; i++){
    levelOrderTraversal(root, i);
  }
}

// Method for breadth first search
public void levelOrderTraversal(Node node, int level){
  if(node == null){
    return;
  }
  if(level == 0){
    System.out.print(node.value + " ");
  }else{
    levelOrderTraversal(node.left, level-1);
    levelOrderTraversal(node.right, level-1);
  }    
}

Breadth first search Non-Recursive Java program

To write a Java program for level order traversal of a binary tree using an iterative method, a queue is used. Initially, root of the tree is inserted to the queue then you need to do the following until queue is empty.

  1. Poll a node from queue and display its value.
  2. Check if node has left child, if yes add that to the queue.
  3. Check if node has right child, if yes add that to the queue.

Iterative approach is considered more efficient than the recursive approach.

Binary Tree- Breadth first search Java program

Full Java program for breadth first search or level order traversal of binary tree.

import java.util.LinkedList;
import java.util.Queue;

public class BinaryTreeBFS {
  // first node
  private Node root;
  BinaryTreeBFS(){
    root = null;
  }
  // Class representing tree nodes
  static class Node{
    int value;
      Node left;
      Node right;
      Node(int value){
        this.value = value;
        left = null;
        right = null;        
      }
      public void displayData(){
        System.out.print(value + " ");
      }
  }
  
  public void insert(int i){
      root = insert(root, i);
  }
      
  //Inserting node to tree using recursion
  public Node insert(Node root, int value){
    if(root == null){
      return new Node(value);
    }
    // Move to the left if passed value is 
    // less than the current node
    if(value < root.value){
      root.left = insert(root.left, value);
    }
    // Move to the right if passed value is 
    // greater than the current node
    else if(value > root.value){
      root.right = insert(root.right, value);
    }
    
    return root;
  }
      
  // Method to get height of the tree
  public int calculateTreeHeight(Node root){
    if(root == null){
      return 0;
    }else{
      // height of left subtree
      int lsh = calculateTreeHeight(root.left);
      // height of right subtree
      int rsh = calculateTreeHeight(root.right);
      // height in each recursive call
      return Math.max(lsh, rsh) + 1;
    }        
  }
      
  public void levelOrder(){
    int height = calculateTreeHeight(root);
    for(int i = 0; i < height; i++){
      levelOrderTraversalRec(root, i);
    }
  }
    
  // Recursive Method for breadth first search
  public void levelOrderTraversalRec(Node root, int level){
      if(root == null){
        return;
      }
      if(level == 0){
        root.displayData();
      }else{
        levelOrderTraversalRec(root.left, level-1);
        levelOrderTraversalRec(root.right, level-1);
      }    
  }
  
  // Iterative Method for breadth first search
  public void levelOrderTraversalItr(Node root){
    if(root == null){
      return;
      }
      Queue<Node> queue = new LinkedList<Node>();
      queue.add(root);
      while(!queue.isEmpty()){
        Node node = queue.poll();
         node.displayData();
         if(node.left != null){
            queue.add(node.left);
         }
         if(node.right != null){
            queue.add(node.right);
         }
      }
  }
      
  public static void main(String[] args) {
    BinaryTreeBFS bst = new BinaryTreeBFS();
      bst.insert(50);
      bst.insert(70);    
      bst.insert(30);
      bst.insert(15);
      bst.insert(35);
      bst.insert(7);
      bst.insert(22);
      bst.insert(31);
      bst.insert(62);
      bst.insert(87);
      System.out.println("Tree Height- " + bst.calculateTreeHeight(bst.root));
      System.out.println("Level order traversal recursive");
      bst.levelOrder();
      System.out.println();
      System.out.println("Level order traversal iterative");
      bst.levelOrderTraversalItr(bst.root);
  }
}

Output

Tree Height- 4
Level order traversal recursive
50 30 70 15 35 62 87 7 22 31 
Level order traversal iterative
50 30 70 15 35 62 87 7 22 31 

Time and space complexity of binary tree level order traversal

With the recursive approach shown in this post which uses the height of the tree the time complexity in worst case is O(n2). Calculation of tree height is O(n) operation if tree is skewed (not well balanced).

For each level i, recursive method takes a top down approach traversing almost the whole tree to find nodes at level i. Which again is O(n) operation. So the total time complexity because of nested loop is O(n2).

Recursion depth is at most the height of the tree h. So the space complexity of recursive approach is O(h) where h may equal n in case of a skewed tree, for balanced tree h equals log(n).

With the iterative approach where Queue data structure is used the time complexity is O(n) as each tree node is visited exactly once.

Space complexity with iterative method is also O(n), as Queue may store upto n/2 elements in worst case.

That's all for this topic Binary Tree Traversal Using Breadth First Search Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Find Minimum and Maximum Value Nodes in Binary Search Tree - Java Program
  2. Java Program to Add and Remove in Graph
  3. Counting Sort Program in Java
  4. Print Odd-Even Numbers Using Threads And wait-notify Java Program
  5. Find Duplicate Characters in a String With Repetition Count Java Program

You may also like-

  1. Zipping Files And Folders in Java
  2. Java Lambda Expression Comparator Example
  3. How to Convert String to Date in Java
  4. Matrix Subtraction Java Program
  5. Batch Processing in Java JDBC - Insert, Update Queries as a Batch
  6. PermGen Space Removal in Java 8
  7. String Comparison in Java equals(), compareTo(), startsWith() Methods
  8. How to Inject Null And Empty String Values in Spring

Java Program to Add and Remove in Graph

In this post we'll see how to write Java program for addition and removal from a graph data structure.

Addition and removal in a graph can be done in the following scenarios-

  1. Adding a vertex
  2. Adding an edge
  3. Removing a vertex
  4. Removing an edge

Another thing to consider while writing Java program for graph addition, removal is the representation of graph-

  1. Graph is represented using adjacency matrix
  2. Graph is represented using adjacency list

Please refer following posts to know more about graph representations- Graph Adjacency Representation - Java Program
Weighted Graph Adjacency Representation - Java Program

Graph addition removal Java program - Adjacency list representation

In the program, Map storing lists of its neighbours is used as adjacency list representation.

A separate class called Vertex is also there to encapsulate vertex information.

Adding a vertex means, adding that vertex as a key in the Map, along with a new ArrayList as a value.

Adding an edge means adding both the start vertex and the end vertex and the reverse link too if it is an undirected graph.

Removing a vertex means removing that particular key from the Map. Also remove where ever the removed vertex is listed as neighbour for other vertices.

Removing an edge means removing the link from starting point to end point, reverse link for the same vertices should also be removed for an undirected graph.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Insert, delete in graph represented as adjacency list
 */
public class GraphDSAL {
  Map<Vertex, List<Vertex>> adjList = new HashMap<>();
  // Vertex class as nested class
  static class Vertex{
    String label;
    Vertex(String label){
      this.label = label;
    }
    public String getLabel() {
      return label;
    }
    public void setLabel(String label) {
      this.label = label;
    }
    @Override
    public int hashCode() {
      return Objects.hash(label);
    }
    @Override
    public boolean equals(Object obj) {
      if (this == obj)
        return true;
      if (obj == null)
        return false;
      if (getClass() != obj.getClass())
        return false;
      Vertex other = (Vertex) obj;
      return Objects.equals(label, other.label);
    }
    
  }
  
  public void addVertex(Vertex v) {
    adjList.putIfAbsent(v, new ArrayList<Vertex>());
  }
  
  public void removeVertex(Vertex v) {
    // remove vertex
    adjList.remove(v);
    // remove where ever the removed vertex is listed as neighbour
    adjList.values().forEach(e -> e.remove(v));
  }
  
  public void addEdge(String source, String destination) {
    Vertex vs = new Vertex(source);
      Vertex vd = new Vertex(destination);
    if(!adjList.containsKey(vs)) {
      addVertex(vs);
    }
    if(!adjList.containsKey(vd)) {
      addVertex(vd);
    }
    adjList.get(vs).add(vd);
    // Reverse link also required for undirected graph
    adjList.get(vd).add(vs);
  }
  
  public void removeEdge(String source, String destination) {
    Vertex vs = new Vertex(source);
      Vertex vd = new Vertex(destination);
      adjList.get(vs).remove(vd);
      // Reverse link removal also required for undirected graph
      adjList.get(vd).remove(vs);
  }
  // Method to display graph
  public void printGraph() {
    adjList.forEach((k, v) -> {
      System.out.print("Vertex " + k.getLabel() + " connects to ");
      v.forEach(e -> System.out.print(e.getLabel() + " "));
      System.out.println();
    });
  }

  public static void main(String[] args) {
    GraphDSAL graph = new GraphDSAL();
    graph.addVertex(new Vertex("A"));
    graph.addEdge("A", "B");
    graph.addEdge("A", "C");
    graph.addEdge("A", "E");
    graph.addEdge("C", "D");
    graph.addEdge("D", "E");
    
    graph.printGraph();
    
    graph.removeVertex(new Vertex("A"));
    //graph.removeEdge("A", "C");
    System.out.println("After removal");
    graph.printGraph();
        
  }

}

Output

Vertex A connects to B C E 
Vertex B connects to A 
Vertex C connects to A D 
Vertex D connects to C E 
Vertex E connects to A D 
After removal
Vertex B connects to 
Vertex C connects to D 
Vertex D connects to C E 
Vertex E connects to D 

Graph addition removal Java program - Adjacency matrix representation

When graph is represented as an adjacency matrix, that means using a 2-D array to represent a graph.

Adding a vertex means, incrementing the rows and columns of the adjacency matrix by 1 to accommodate new vertex. Copy the rows and columns from the old adjacency matrix to this new one and then assign the new adjacency matrix as the adjacency matrix of the graph.

Adding an edge means changing the row, column value to 1 for the array element, mapping to the start and end vertices for the added edge.

Removing a vertex means, decrementing the rows and columns of the adjacency matrix to represent removal of a vertex. While copying the rows and columns from the old adjacency matrix to this new one ensure that the values for the row and column represented by the removed vertex are not added to the new adjacency matrix. Assign the new adjacency matrix as the adjacency matrix of the graph.

Removing an edge means changing the row, column value to 0 for the array element, mapping to the start and end vertices for the removed edge.

/**
 * Insert, delete in graph represented as adjacency matrix
 */
public class GraphDSAM {
  private int vertices;
  private int[][] adjMatrix;
  
  GraphDSAM(int vertices){
    this.vertices = vertices;
    adjMatrix = new int[vertices][vertices];
  }
  
  public void addEdge(int source, int destination) {
    if((source < 0 || source >= vertices) || (destination < 0 || destination >= vertices)) {
      System.out.println("Invalid edge addition");
      return;
    }
    adjMatrix[source][destination] = 1;
    // For undirected graph reverse setting also required
    adjMatrix[destination][source] = 1;
  }
  
  public void removeEdge(int source, int destination) {
    if((source < 0 || source >= vertices) || (destination < 0 || destination >= vertices)) {
      System.out.println("Invalid edge removal");
      return;
    }
    adjMatrix[source][destination] = 0;
    // For undirected graph reverse setting also required
    adjMatrix[destination][source] = 0;
  }
  
  public void addVertex() {
    int changedSize = vertices + 1;
    int[][] changedAdjMatrix = new int[changedSize][changedSize];

    // Copy existing connections
    for (int i = 0; i < vertices; i++) {
      for (int j = 0; j < vertices; j++) {
        changedAdjMatrix[i][j] = adjMatrix[i][j];
      }
    }
    this.adjMatrix = changedAdjMatrix;
    vertices = changedSize;
  }
  
  public void removeVertex(int v) {
    if(v < 0 || v >= vertices){
      System.out.println("Invalid vertex removal");
      return;
    }
    int[][] changedAdjMatrix = new int[vertices-1][vertices-1];
    // maintaining row for changedAdjMatrix
    int tempRow = 0;
    
    for(int i = 0; i < adjMatrix.length; i++) {
      if(i == v) {
        continue;
      }
      // maintaining col for changedAdjMatrix
      int tempCol = 0;
      for(int j = 0; j < adjMatrix[0].length; j++) {
        if(j == v) {
          continue;
        }
        changedAdjMatrix[tempRow][tempCol] = adjMatrix[i][j];
        tempCol++;
      }
      tempRow++;
      
    }
    this.adjMatrix = changedAdjMatrix;
  }
  
  public void printGraph() {
    for(int i = 0; i < adjMatrix.length; i++) {
      for(int j = 0; j < adjMatrix[0].length; j++) {
        System.out.print(adjMatrix[i][j] + "\t");
      }
      System.out.println();
    }
  }
  
  public static void main(String[] args) {
    GraphDSAM graph = new GraphDSAM(5);
    graph.addEdge(0, 1);
    graph.addEdge(0, 2); 
    graph.addEdge(0, 4); 
    graph.addEdge(2, 3); 
    graph.addEdge(3, 4); 

    graph.printGraph();
    
    System.out.println("After adding a vertex");
    graph.addVertex();
    graph.addEdge(3, 5); 
    graph.printGraph();
    System.out.println("After removal");
    graph.removeEdge(3, 4);
    graph.printGraph();

  }

}

Output

0	1	1	0	1	
1	0	0	0	0	
1	0	0	1	0	
0	0	1	0	1	
1	0	0	1	0	
After adding a vertex
0	1	1	0	1	0	
1	0	0	0	0	0	
1	0	0	1	0	0	
0	0	1	0	1	1	
1	0	0	1	0	0	
0	0	0	1	0	0	
After removal
0	1	1	0	1	0	
1	0	0	0	0	0	
1	0	0	1	0	0	
0	0	1	0	0	1	
1	0	0	0	0	0	
0	0	0	1	0	0	

That's all for this topic Java Program to Add and Remove in Graph. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Binary Tree Traversal Using Breadth First Search Java Program
  2. Binary Tree Traversal Using Depth First Search Java Program
  3. Binary Tree Implementation in Java - Insertion, Traversal And Search
  4. Sorted Linked List In Java
  5. Deque Implementation in Java Using Doubly Linked List

You may also like-

  1. Rabin-Karp Algorithm For Pattern Search - Java Program
  2. Two Sum - Elements in Array With Given Sum Java Program
  3. Java Program - Sieve of Sundaram to Find Prime Numbers
  4. How to Create Password Protected Zip File in Java
  5. Java CyclicBarrier With Examples
  6. static Reference to The Non-static Method or Field Error
  7. Difference Between @Controller And @RestController Annotations in Spring
  8. How to Create a Custom Structural Directive in Angular

Wednesday, October 15, 2025

Java Program to Check Prime Number

In this post we'll see a Java program to check whether given number is a prime number or not.

As we know that a number is a prime number if it is a natural number greater than 1 and it can be divided either by 1 or by the number itself. As example- 2, 3, 5, 7, 11, 13, 17 ….

First thing that may come to mind, while writing Java program for checking prime number, is to have a variable in a for loop that starts from 2 (as 1 will always divide the number) and increment it by one until it reaches the number that is checked for being prime number or not. In every iteration of the loop divide the number by variable, if remainder is zero at any time then the checked number is not a prime number.

That loop would look something like this-

for(int i = 2; i < num; i++){
  if(num % i == 0){
    flag = false;
    break;
  }
}

But that logic can be made more efficient. To check if a number is prime or not you need to run a loop starting from 2 till number/2 to check if number has any divisor.

For example, if number is 8 then you just need to check till 4 (8/2) to see if it divides by any number or not. Same way if you have a number 15 you just need to check till 7 to see if it divides completely by any number or not. We'll use the same logic to write our program to check for prime number.

Java program to check prime number or not

import java.util.Scanner;

public class PrimeCheck {
  public static void main(String[] args) {
    // take input from the user
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number: ");

    int num = sc.nextInt();
    boolean flag = isPrime(num);
    if(flag){
      System.out.println(num + " is a prime number.");
    }else{
      System.out.println(num + " is not a prime number.");
    }
  }
    
  private static boolean isPrime(int num){
    boolean flag = true;
    // loop from 2, increment it till number/2
    for(int i = 2; i <= num/2; i++){
      // no remainder, means divides 
      if(num % i == 0){
        flag = false;
        break;
      }
    }
    return flag;
  }
}

Output

Enter number: 
16
16 is not a prime number.

Enter number: 
31
31 is a prime number.

Here scanner class is used to get input from the user.

Refer How to Read Input From Console in Java to see other ways to get input from user.

That's all for this topic Java Program to Check Prime Number. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Java Program to Display Prime Numbers
  2. Java Program - Sieve of Eratosthenes to Find Prime Numbers
  3. Java Program - Sieve of Sundaram to Find Prime Numbers
  4. Armstrong Number or Not Java Program
  5. Fibonacci Series Program in Java

You may also like-

  1. Reading File in Java Using BufferedReader
  2. Count Number of Words in a String Java Program
  3. Abstraction in Java
  4. Inheritance in Java
  5. static Keyword in Java With Examples
  6. Difference Between ReentrantLock and Synchronized in Java
  7. Dependency Injection in Spring Framework
  8. Difference Between Checked And Unchecked Exceptions in Java

Java Program to Display Prime Numbers

This post shows a Java program to display prime numbers.

As we know that a number is a prime number if it is a natural number greater than 1 and it can be divided either by 1 or by the number itself. As example- 2, 3, 5, 7, 11, 13, 17 ….

To check if a number is prime or not you need to run a loop starting from 2 till number/2 to check if number has any divisor.

For example, if number is 8 then you just need to check till 4 (8/2) to see if it divides by any number or not. Same way if you have a number 15 you just need to check till 7 to see if it divides completely by any number or not. We'll use the same logic to write our program to display prime numbers up to the given upper range.

Looking for more efficient way to display prime numbers. Refer these sieving algorithms- Java Program - Sieve of Eratosthenes to Find Prime Numbers, Java Program - Sieve of Sundaram to Find Prime Numbers