Friday, October 31, 2025

Varargs (Variable-length Arguments) in Java

varargs in Java, short for variable-length arguments is a feature that allows the method to accept variable number of arguments (zero or more). With varargs it has become simple to create methods that need to take a variable number of arguments. The feature of variable argument (varargs) has been added in Java 5.


Syntax of varargs

A vararg in Java is specified by three ellipsis (three dots) after the data type, its general form is

return_type method_name(data_type ... variableName){
 ..
 ..
}  

Python String isnumeric() Method

The isnumeric() method in Python String class is used to check if all the characters in the string are numeric characters or not.

isnumeric() method returns true if all characters in the string are numeric characters and there is at least one character, false otherwise. Numeric characters include digits (0..9) and all characters that have the Unicode numeric value property like superscripts or subscripts (as example 26 and 42), fractions like ¼.

Note that numbers with negative sign like '-123' and with decimal sign like '56.78' are not considered as numbers by isnumeric() method. Same way number in exponential notation like '1.23E+10' is also not considered number.

Python isnumeric method examples

1. Using isnumeric() method to check if all the characters are digits or not.

str = '345'
print(str)
print(str.isnumeric())

str = 'A12B'
print(str)
print(str.isnumeric())

Output

345
True
A12B
False

2. Using isnumeric() method with negative, decimal numbers. For such strings isnumeric() method returns false.

  
  str = '-123'
print(str)
print(str.isnumeric())

str = '45.67'
print(str)
print(str.isnumeric())

str = '1.23E+10'
print(str)
print(str.isnumeric())

Output

-123
False
45.67
False
1.23E+10
False

3. Using isnumeric() method with superscripts or subscripts. For such strings isnumeric() method returns true.

str = '2\u2076'
print(str)
print(str.isnumeric())

str = '4\u2082'
print(str)
print(str.isnumeric())

Output

26
True
42
True

4. Using isnumeric() method with characters that have Unicode numeric value property.

s = '\u246D' #CIRCLED NUMBER FOURTEEN ?
print(s)
print(s.isnumeric())

s = '\u2474' #PARENTHESIZED DIGIT ONE ?
print(s)
print(s.isnumeric())

s = '\u248C' # DIGIT FIVE FULL STOP ?
print(s)
print(s.isnumeric())

s = '\u24B0' #PARENTHESIZED LATIN SMALL LETTER U ?
print(s)
print(s.isnumeric())

Output

⑭
True
⑴
True
⒌
True
⒰
False

That's all for this topic Python String isnumeric() Method. 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 isdigit() Method
  2. Changing String Case in Python
  3. Local, Nonlocal And Global Variables in Python
  4. Abstract Class in Python
  5. Global Keyword in Python With Examples

You may also like-

  1. Python assert Statement
  2. Interface in Python
  3. Python Exception Handling - try,except,finally
  4. Convert String to int in Python
  5. Java Multithreading Tutorial
  6. String in Java Tutorial
  7. Spring Web MVC Tutorial
  8. Spring Web Reactive Framework - Spring WebFlux Tutorial

Detect Cycle in an Undirected Graph Using BFS - Java Program

In the post Detect Cycle in an Undirected Graph Using DFS - Java Program we saw how to detect a cycle in an undirected graph using DFS, in this tutorial we'll see how to write a Java program to detect a cycle in an undirected graph using breadth-first search traversal.

For example, in the following graph 0-2-3-4-0 is a cycle.

Undirected Graph Cycle

Refer post Java Program - Breadth First Search (BFS) Traversal For Graph to know in details about breadt-first search traversal of a graph.

Detecting a cycle in an undirected graph

Logic for detecting a graph with graph traversal is simple. If the vertex currently visited has already been visited that means there is a cycle in the graph.

With undirected graph, you also have to consider the fact that the connection between vertices is considered bi-directional. Edge between A and B also means an edge between B and A. This bi-directional connection should not be considered a cycle. For this reason, you also need to keep track of the parent vertex of the current vertex. When list of the adjacent vertices for the current vertex is iterated, connection back to the parent vertex should be ignored.

Cycle detection in an undirected graph using BFS - Java Program

In the Java program adjacency list is used to represent the graph. There is a visited array to keep track of the vertices which are already visited.

Program also displays the vertices which are part of the cycle, a HashMap is used to store the vertices that are part of the cycle.

BFS traversal and the cycle detection logic is in the bfs() method which uses a queue to store the adjacent vertices. You also need to keep track of the parent therefore queue adds the vertex and its parent vertex both as an array.

Queue<int[]> queue = new LinkedList<>();

While traversing the graph using breadth-first search, if you come across a vertex that is already visited but not the parent of the current vertex that means there is a cycle.

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

public class UndirectedGraphCycleBFS {
  private Map<Integer, List<Integer>> adjList;
  private int numOfVertices;

  UndirectedGraphCycleBFS(int numOfVertices){
    this.numOfVertices = numOfVertices;
    adjList = new HashMap<>();
  }
  
  // Creating adjacency list 
  public void addEdge(Integer source, Integer destination) {
    adjList.computeIfAbsent(source, k->new ArrayList<>()).add(destination);
    // For undirected graph
    adjList.computeIfAbsent(destination, k->new ArrayList<>()).add(source);
  }
  
  public void printGraph() {
    adjList.forEach((k, v) -> {
      System.out.print("Vertex " + k + " Connectes to ");
      v.forEach(e -> System.out.print(e + " "));
      System.out.println();
    });
  }
  
  /*Cycle detection logic starts here */
  public boolean isCycleDetected() {
    boolean[] visited = new boolean[numOfVertices];
    for(int i = 0; i < numOfVertices; i++) {
      if(!visited[i]) {
        if(bfs(i, visited)) {
          return true;
        }
      }
    }
    return false;
  }
  
  private boolean bfs(int currentVertex, boolean[] visited) {
    // Queue needs to add parent info for the current vertex
    Queue<int[]> queue = new LinkedList<>();
    // For starting vertex parent is -1
    queue.add(new int[]{currentVertex, -1});
    visited[currentVertex] = true;
    // This map is used to keep track of the vertices that are part of the cycle
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    map.put(currentVertex, -1);

    while(!queue.isEmpty()) {
      int[] v = queue.poll();
      int node = v[0];
      int parent = v[1];          
      for(int n : adjList.get(node)) {
              
        if(!visited[n]) {
          visited[n] = true;
          queue.add(new int[]{n, node});
          map.put(n, node);
        }else if(n != parent) { // cycle detected
          // display vertices that are part of the cycle
          printCycle(map, node, n);
          return true;
        }
      }               
    }
    return false;
  }
  
  // Helper method to print the cycle vertices
  private void printCycle(Map<Integer, Integer> parentMap, int u, int v) {
    List<Integer> cycle = new ArrayList<>();
    // Start from the node that caused the cycle detection
    cycle.add(v); 

    int current = u;
    while (current != -1 && current != v) {
      cycle.add(current);
      current = parentMap.get(current);
    }
    Collections.reverse(cycle); // Reverse to get the cycle in order
    cycle.add(parentMap.get(v)); // Add the last vertex
   
    System.out.println("Cycle vertices: " + cycle);
  }
  
  public static void main(String[] args) {
    UndirectedGraphCycleBFS graph = new UndirectedGraphCycleBFS(10);
        
    
//  graph.addEdge(0, 1);
//  graph.addEdge(0, 2);
//  graph.addEdge(0, 3);
//  graph.addEdge(0, 7); 
//  graph.addEdge(1, 4);
//  graph.addEdge(4, 5);
//  graph.addEdge(2, 5);
//  graph.addEdge(3, 6);// Creates a cycle 0-1-4-5-2-0

    
    graph.addEdge(0, 1); 
    graph.addEdge(0, 2); 
    graph.addEdge(0, 4); 
    graph.addEdge(2, 3);
    graph.addEdge(3, 4);// Creates a cycle [0, 2, 3, 4, 0]
        
    graph.printGraph(); 
    
    if(graph.isCycleDetected()) {
      System.out.println("Cycle found in the graph");
    }else {
      System.out.println("No cycle found in the graph");
    }

  }

}

Output

Vertex 0 Connectes to 1 2 4 
Vertex 1 Connectes to 0 
Vertex 2 Connectes to 0 3 
Vertex 3 Connectes to 2 4 
Vertex 4 Connectes to 0 3 
Cycle vertices: [0, 4, 3, 2]
Cycle found in the graph

Time and space complexity of cycle detection in an undirected graph using BFS

With adjacency list only adjacent vertices are stored as a list for each vertex. For each vertex, the DFS 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).

Extra space is needed for visited array which is O(V). 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). Thus, the space complexity can be considered as O(V).

Note that storing adjacency list is also O(V + E) in case you want to include input graph too in the space complexity.

That's all for this topic Detect Cycle in an Undirected Graph Using BFS - 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. Weighted Graph Adjacency Representation - Java Program
  2. Java Program to Add and Remove in Graph
  3. Java Program - Depth First Search (DFS) Traversal For Graph
  4. Find Minimum and Maximum Value Nodes in Binary Search Tree - Java Program
  5. Java Program to Create Your Own BlockingQueue

You may also like-

  1. Manacher's Algorithm to Find The Longest Palindrome - Java Program
  2. Reading Delimited File in Java Using Scanner
  3. How to Create PDF From XML Using Apache FOP
  4. Find The Maximum Element in Each Row of a Matrix Java Program
  5. Just In Time Compiler (JIT) in Java
  6. Spring MVC File Download Example
  7. Passing Query Parameters in Angular Routing
  8. Named Tuple in Python

Thursday, October 30, 2025

static Import in Java With Examples

In order to access any static member (static field or method) of a class, it is necessary to qualify references with the class they have come from.

ClassName.static_method()

With static import feature of Java 5, members defined in a class as public static can be used without qualifying it with the class name, in any Java class which does a static import. So, static import in Java allows unqualified access to the static member. This shortens the syntax required to use a static member.

Syntax of static import in Java

Any Java program can import the members individually or en masse-

// accessing specific static variable of a class
import static package_name.class_name.static_variable;

// accessing specific static method of a class
import static package_name.class_name.static_method;

// accessing all the static members of a class en masse
import static package_name.class_name.*;

Detect Cycle in an Undirected Graph Using DFS - Java Program

In this post we'll see how to detect a cycle in an undirected graph using depth-first search traversal.

For example, in the following graph 0-2-3-4-0 is a cycle.

Undirected Graph Cycle

Refer post Java Program - Depth First Search (DFS) Traversal For Graph to know in details about DFS traversal of a graph.

Detecting a cycle in an undirected graph

Logic for detecting a graph with graph traversal is simple. If the vertex currently visited has already been visited that means there is a cycle in the graph.

With undirected graph, you also have to consider the fact that the connection between vertices is considered bi-directional. Edge between A and B also means an edge between B and A. This bi-directional connection should not be considered a cycle. For this reason, you also need to keep track of the parent vertex of the current vertex. When list of the adjacent vertices for the current vertex is iterated, connection back to the parent vertex should be ignored.

Cycle detection in an undirected graph - Java Program

In the Java program, adjacency list is used to represent the graph. There is a visited array to keep track of the vertices which are already visited.

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

Program also displays the vertices which are part of the cycle, stack is used to store those vertices.

DFS traversal and the cycle detection logic is in the dfs() method which is called recursively with the adjacent vertex of the current vertex to keep going deep in the current branch. You also keep track of the parent and make a check to ignore such bi-directional connection.

if(v == parent) {			
  continue;
}

Here is the complete Java program

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

/**
 * Undirected graph cycle detection using DFS
 */
public class UndirectedGraphCycle {
  private Map<Integer, List<Integer>> adjList;
  private int numOfVertices;
  private Stack<Integer> stack;
  UndirectedGraphCycle(int numOfVertices){
    this.numOfVertices = numOfVertices;
    adjList = new HashMap<>();
    // to keep track of the vertex for the cycle, stack is used
    // so that vertices which are visited and not part of the cycle
    // can be easily popped
    stack = new Stack<>();
  }
  
  public void addEdge(Integer source, Integer destination) {
    adjList.computeIfAbsent(source, k->new ArrayList<>()).add(destination);
    // For undirected graph
    adjList.computeIfAbsent(destination, k->new ArrayList<>()).add(source);
  }
  
  public void printGraph() {
    adjList.forEach((k, v) -> {
      System.out.print("Vertex " + k + " Connectes to ");
      v.forEach(e -> System.out.print(e + " "));
      System.out.println();
    });
  }
  
  public boolean isCycleDetected() {
    boolean[] visited = new boolean[numOfVertices];
    for(int i = 0; i < numOfVertices; i++) {
      if(!visited[i]) {
        if(dfs(i, visited, -1)) {
          return true;
        }
      }
    }
    return false;
  }
  
  // Uses DFS traversal (recursive) to detect a cycle
  private boolean dfs(int currentVertex, boolean[] visited, int parent) {
    visited[currentVertex] = true;
    stack.push(currentVertex);

    for(int v : adjList.get(currentVertex)) {
      System.out.println("Vertex " + v + " Currentv " + currentVertex);
      // undirected graph means 2 way connection so 
      // connection back to parent doesn't mean cycle
      if(v == parent) {
        
        continue;
      }
      // visited array at index is true means that vertex is already visited
      // means a cycle
      if(visited[v]) {
        /*Start - To display the vertices which are part of the cycle */
        List<Integer> cycle = new ArrayList<>();
        int startIndex = stack.indexOf(v);
        for (int i = startIndex; i < stack.size(); i++) {
          cycle.add(stack.get(i));
        }
        // Add the starting node to complete the cycle
        cycle.add(v); 
        System.out.println("Detected cycle is " + cycle);
        /*Display logic ends here comment from start to end 
         * if cycle display not needed*/
        return true;
      }
      // recursive call
      if(dfs(v, visited, currentVertex))
        return true;
    }
    // reached here means current vertex is not part of the cycle so pop it
    stack.pop();
    return false;
  }
  
  public static void main(String[] args) {
    UndirectedGraphCycle graph = new UndirectedGraphCycle(5);

    graph.addEdge(0, 1); //A-B
    //graph.addEdge(1, 2); //A-C
    graph.addEdge(0, 2); //A-C
    graph.addEdge(0, 4); //A-E
    graph.addEdge(2, 3); //C-D
    graph.addEdge(3, 4); //D-E
    
    graph.printGraph(); 
    if(graph.isCycleDetected()) {
      System.out.println("Cycle detected in the graph");
    }else {
      System.out.println("No Cycle detected in the graph");
    }
  }
}

Output

Vertex 0 Connectes to 1 2 4 
Vertex 1 Connectes to 0 
Vertex 2 Connectes to 0 3 
Vertex 3 Connectes to 2 4 
Vertex 4 Connectes to 0 3 
Detected cycle is [0, 2, 3, 4, 0]
Cycle detected in the graph

Time and space complexity of cycle detection in an undirected graph

With adjacency list only adjacent vertices are stored as a list for each vertex. For each vertex, the DFS 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).

Extra space is needed for visited array which is O(V). 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). Thus, the space complexity can be considered as O(V).

Note that space for storing adjacency list is O(V + E), in case you want to include input graph too in the space complexity.

That's all for this topic Detect Cycle in an Undirected Graph Using DFS - 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. Weighted Graph Adjacency Representation - Java Program
  2. Java Program to Add and Remove in Graph
  3. Java Program - Breadth First Search (BFS) Traversal For Graph
  4. Java Program to Delete a Node From Binary Search Tree (BST)
  5. How to Remove Elements From an Array Java Program

You may also like-

  1. Rabin-Karp Algorithm For Pattern Search - Java Program
  2. How to Sort Elements in Different Order in Java TreeSet
  3. Find Largest and Second Largest Number in Given Array Java Program
  4. How to Display Time in AM-PM Format in Java
  5. CopyOnWriteArrayList in Java With Examples
  6. Spring Boot Microservice Circuit Breaker Using Resilience4j
  7. NgNonBindable Directive in Angular
  8. Accessing Characters in Python String

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