Java Strings: Length
In Java, a string is a collection of characters, or an array of characters. The term array is an important one in Java and many other programming languages. An array is an ordered collection of data stored in one place. They are very useful when storing a large amount of related data like student records. They also come with a rage of useful methods. Since a string is an array of characters, many of these array methods are available to strings.
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 are 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 the following 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.