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

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