Java String length
If we want to calculate the length of the string (by length of string, we mean the number of Unicode characters in the string), we can make use of the length method, which returns us the length of the given string.
Here is the program for the method, length(), which helps us get the length of the string. Have a look at the program →
public class StringMethods {
public static void main(String[] args) {
String exampleString = new String(“Hello from GyaniPandit”);
int stringLength = exampleString.length();
System.out.println(“the length of the string: ” + stringLength);
}
}
So, the length of the string in our case is found to be 22. You can execute the program for another input. We can also have an empty string, which is just a string with a length of zero. To have an empty string, we just have to do the following. Have a look at this program →
public class StringMethods {
public static void main(String[] args) {
// String exampleString = new String(); → This will also get us an empty string.
String exampleString = “”; // or this too…
int stringLength = exampleString.length();
System.out.println(“the length of the string: ” + stringLength);
}
}
So, if you type in the above code into the IntelliJ idea or any other IDE that you are using or even some text editor, you will find that the length of the string is always zero. You also can observe that there are two ways to create an empty string. Try running the program and observe the output yourself.
One more thing is that when we initialize the string variable to null, this does mean that it does not point to any string. This is different from the empty string. This is how we initialize a string variable to null-
String exampleString = null;
So, in short, we had to discuss how can we use the method length() to calculate the length of a string, and now we know how we do it. So, now let’s move to the next method.