Thursday, November 6, 2025

@if in Angular With Examples

In this article we'll see how to use @if template syntax in Angular with examples.

@if in Angular

The @if built-in control flow block was introduced in Angular 17, which allows you to conditionally render in Angular templates based on whether the condition is true or false.

This new @if syntax is more concise and intuitive and closer to if-else statement in Javascript. Thus, it is a better alternative than the traditional *ngIf directive in Angular.

With @if, there is also support for @else if and @else statements making the syntax for the full @if block as given below-

@if (condition) {
  <!-- Content to display if the condition is true -->
} @else if (anotherCondition) {
  <!-- Content to display if anotherCondition is true and the first condition is false -->
} @else {
  <!-- Content to display if all preceding conditions are false -->
}

With @if block there is a conditional expression. If the condition evaluates to true, the content within the @if block is rendered in the DOM.

If the condition is false, Angular checks for an @else if block. If an @else if block exists and its anotherCondition is true, its content is rendered.

If @if and @else if (which can occur multiple times) conditions are false, the content within the @else block (if present) is rendered.

If there is only @if block and no @else or @else if blocks are present, the content within the @if block is removed from the DOM, if the condition given with @if is false.

Note that, if you are using *ngIf with standalone component then you need to import either NgIf or CommoModule, whereas @if is a part of the template engine itself, which means it is directly available for use without any explicit imports, which is also an advantage of using @if block in Angular.

@if in Angular example

1. Following example uses @if with @else to show different messages based on whether the loggedIn property is true or false.

import { Component } from '@angular/core';

@Component({
  selector: 'app-ifdemo',
  standalone: true,

  template: `
    @if(loggedIn){
      <p>Welcome back</p>
    }@else {
      <p>Please log in</p>
    }`,
})
export class IfdemoComponent {
  loggedIn: boolean = true;
}

2. Here is another example which uses @if, @else if and @else in Angular.

import { Component } from '@angular/core';

@Component({
  selector: 'app-ifdemo',
  standalone: true,

  template: `
    @if(a > b){
      <p>{{a}} is greater than {{b}}</p>
    }@else if(b > a){
      <p>{{b}} is greater than {{a}}</p>
    }@else {
      <p>{{b}} and {{a}} are equal</p>
    }`,
})
export class IfdemoComponent {
 a = 22;
 b = 20;
}

That's all for this topic @if in Angular With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. @for in Angular With Examples
  2. Angular ngSwitch Directive With Examples
  3. Angular ngIf Directive With Examples
  4. Angular ngStyle Directive With Examples
  5. Directives in Angular

You may also like-

  1. Angular First App - Hello world Example
  2. Angular Class Binding With Examples
  3. Angular Two-Way Data Binding With Examples
  4. CanDeactivate Guard in Angular With Example
  5. Unmodifiable or Immutable List in Java
  6. Initializer Block in Java
  7. java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java
  8. Python Program to Display Armstrong Numbers

Wednesday, November 5, 2025

@for in Angular With Examples

In this article we'll see how to use @for block in Angular with examples.

@for in Angular

The @for block in Angular is a built-in control flow syntax used to repeatedly loop and render content in a template for each item in an iterable.

@for control flow statement is added in Angular 17 and provides a cleaner syntax than using the ngFor directive in Angular.

Syntax of @for block

@for (item of items; track item.id) {
  <!-- Content to repeat for each item -->
} @empty {
  <!-- Optional content to display if the collection is empty -->
}

Here item variable is assigned the value of each item in the collection.

The 'items' represents the collection to be iterated over. This collection can be an array, a string, or anything that is iterable.

The value of the track expression should be a unique identifier for each item in the collection for example id property, or a value that uniquely identifies each item. Note that the track expression is required.

@empty: This is an optional block that renders its content only if the items collection is empty.

@for example in Angular

1. Looping a simple array of strings

fordemo.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-fordemo',
  standalone: true,
  imports: [],
  templateUrl: './fordemo.component.html',
  styleUrl: './fordemo.component.css'
})
export class FordemoComponent {
  items = ['Ram', 'CPU', 'Mouse', 'Keyboard'];
}

fordemo.component.html

<ul>
  @for(item of items; track item){
    <li>{{item}}</li>
  }  
</ul>

Then import the component in the AppComponent

import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { FordemoComponent } from "./ControlFlow/fordemo/fordemo.component";

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, FordemoComponent],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'myApp';
}

And you are ready to use it in app.component.html

<app-fordemo />

That should give you the output as a list of items

•	Ram
•	CPU
•	Mouse
•	Keyboard

2. Looping an array of objects

fordemo.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-fordemo',
  standalone: true,
  imports: [],
  templateUrl: './fordemo.component.html',
  styleUrl: './fordemo.component.css'
})
export class FordemoComponent {
  products = [
    {id:1, name:'Ram', price:45.67}, 
    {id:2, name:'CPU', price:175.67}, 
    {id:3, name:'Mouse', price:23}, 
    {id:3, name:'Keyboard', price:50}
  ];
}

fordemo.component.html

<ul>
  @for(product of products; track product.id){
    <li>{{product.name}} {{product.price}}</li>
  }
</ul>

As you can see now item.id is used as track expression, which should be unique for each item.

3. @for with $empty

<ul>
  @for(item of items; track $index){
    <li>{{item}}</li>

  }@empty {
    <li>There are no items.</li>
  }
</ul>

In the ts file, if items array is empty

items = [];

then $empty block is rendered.

Why is track expression required

As already mentioned, the track expression is required, omitting it results in "@for loop must have a "track" expression" error.

Providing track expression is crucial for performance optimization. It helps Angular efficiently identify and update DOM elements when the underlying data changes, preventing unnecessary re-rendering of the entire list.

Track expression determines a key used to associate array items with the views in the DOM. Having that clear item identity allows Angular to execute a minimal set of DOM operations as items are added, removed or moved in a collection.

For example, if you are adding a new element to an array of length 100, Angular should be able to identify its id as a new id and just append that new element to the DOM, without having to re-render all the other elements.

Using $index as tracking mechanism

$index is one of the implicit variable available with @for, which provides the index of the current row. This $index can also be used as track expression.

<ul>
  @for(item of items; track $index){
    <li>{{item}}</li>
  }
</ul>

track $index should only be preferred as tracking mechanism if collection which is iterated is static. For dynamic collections with frequent additions, deletions, or reordering, opt for a unique property of each item as the tracking key.

Contextual variables available with @for

Within the @for block, you can access several built-in contextual variables using a let expression, such as:

  1. $count- Number of items in a collection iterated over
  2. $index- Index of the current row
  3. $first- Whether the current row is the first row
  4. $last- Whether the current row is the last row
  5. $even- Whether the current row index is even
  6. $odd- Whether the current row index is odd

@for with $index example

Template code

@for(product of products; track product.id; let idx = $index){
    <p>Product #{{ idx+1 }}: {{product.name}} {{product.price}}</p> 
}

If you call it with the following array in .ts file

  products = [
    {id:1, name:'Ram', price:45.67}, 
    {id:2, name:'CPU', price:175.67}, 
    {id:3, name:'Mouse', price:23}, 
    {id:3, name:'Keyboard', price:50}
  ];

Then the output is

Product #1: Ram 45.67
Product #2: CPU 175.67
Product #3: Mouse 23
Product #4: Keyboard 50
Note that index is zero based. 

@for with $odd and $even example

If you want to render a table with odd and even rows in different colours then that can be done using the $odd or $even implicit variable.

fordemo.component.html

<h2>Product Details</h2>
<table border="1">
  <tr>
    <th>S. No</th>
    <th>Id</th>
    <th>Name</th>
    <th>Price</th>
  </tr>
  @for(product of products; track product.id; let idx = $index; let odd = $odd){
    <tr [class.bg]="!odd">
        <td>{{idx+1}}</td>
        <td>{{product.id}}</td>
        <td>{{product.name}}</td>
        <td>{{product.price}}</td>
    </tr>
    
    }
</table>

Note that, class binding in Angular is used here to bind CSS class. The variable odd returns true or false based on whether the row position is even or odd.

fordemo.component.css

.bg{
    background-color: yellow;  
}

fordemo.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-fordemo',
  standalone: true,
  imports: [],
  templateUrl: './fordemo.component.html',
  styleUrl: './fordemo.component.css'
})
export class FordemoComponent {
  products = [
    {id:1, name:'Ram', price:45.67}, 
    {id:2, name:'CPU', price:175.67}, 
    {id:3, name:'Mouse', price:23}, 
    {id:3, name:'Keyboard', price:50}
  ];
}
@for in Angular

That's all for this topic @for in Angular With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. @if in Angular With Examples
  2. Angular ngSwitch Directive With Examples
  3. Angular ngIf Directive With Examples
  4. Angular ngStyle Directive With Examples
  5. Directives in Angular

You may also like-

  1. Angular First App - Hello world Example
  2. Angular Class Binding With Examples
  3. Angular Two-Way Data Binding With Examples
  4. CanDeactivate Guard in Angular With Example
  5. Unmodifiable or Immutable List in Java
  6. Initializer Block in Java
  7. java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java
  8. Python Program to Display Armstrong Numbers

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