OneBite.Dev - Coding blog in a bite size

count a string length in java

Code snippet on how to count a string length in java

public static int countStringLength(String string) { 
    int length = 0; 
  
    for (int i = 0; i < string.length(); i++) { 
        length++; 
    } 
  
    return length; 
} 

This code snippet calculates the length of a String. The code begins by declaring a variable ‘length’ and initializing it to 0. Then, it invokes the length() method on the String that is passed as parameter. The length() method returns an integer value which is the number of characters present in the String. The for-loop iterates through each character of the String and increments the length. Finally, it returns the length of the String.

java