length of a string in java(3 approaches)
In this article you can learn how to find the length of a string in java with 3 different approaches.
Approach:-1 "find length of a string in java by charAt()"
public class bycharAt {
public static void main(String[] args) {
String name = "codeyourslf";
int i = 0;
try{
for(i = 0; ; i++){
name.charAt(i);
}
}
catch(Exception e){
}
System.out.println("The length of the string is: "+i);
}
}
In this program we can able to find the length of a string using exception concept.
See in the for loop, I have define the starting value(i = 0) but I have not set the ending limit. So loop with go upto the length of that string because inside the loop I have used stringName.charAt(i).
This charAt(i) will iterate all the index of the string I mean upto the length of the string.
After iterating all the index in the string, it will not stop as I have not set the limit. But in the other hand there is nothing left in the string to iterate.
So it will give an exception, that I have handled in the catch block and after that I have printed i which is the number of iterations i.e length of the string.
Output
Approach:-2 "find the length of string in java using length() method"
import java.util.Scanner;
public class byMethod {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String: ");
String s = sc.next();
System.out.println("The length of the string is: "+ s.length());
}
}
We have a inbuilt method to count the length of any string i.e length() method.
By using stringName.length() we can easily find out the length of any string.
Approach:-3 "length of a string in java without length() method"
Here I use toCharArray() method
public class bytoChar {
public static void main(String[] args){
String name = "codeyourslf";
int length = 0;
for(char c: name.toCharArray()){
length = length + 1;
}
System.out.println("The length is: "+length);
}
}
In this program I haven't use the length() method, here I have converted the string into character array as a result we can easily iterate it.
Here you can realise that the number iteration is equal to the number of individuals character present in the string, which is the length of string.
Previously I have defined a length variable with value 0, at each iteration I have incremented the value by 1.
Finally we can get the total length of that string inside length variable.