Java Strings: Length
The length() method
Consider the following string definition and initialisation:
String myString = "Learning Glue";
We can see that the string variable name is myString and it has a value of Learning Glue, and that the number of characters that it contains (including spaces, they’re characters too) – is 13. We can test this using the length() method that will return the number of characters of a given String. This method is predefined in the Java language so we don’t have to write it ourselves. The general syntax is:
In practice we will replace String with the name of a variable that contains a string that we wish to get the length of, for example:
This will execute the length() method and return a value but it will be immediately lost unless we use it, for example display it or store it in a variable. Let’s simply display it type this into your IDE:
System.out.println("The length is " + myString.length());
What result did you expect, and did you get that?
- You should have expected an integer, the length() method will return an integer
- The length() method will return an integer that is equal to the number of characters in a string, all characters including spaces, so the string “Learning Glue” would return a length of 13
You will find the length() method very useful and it has a number of other uses beyond Strings so we will meet it again.