Length Method

This is going to be the shortest post in this series because there’s really not much to the Java length method on a string. All it does is return the number of characters in the string.

There is one point of confusion though, and that goes back to what we talked about in the first post where 0 is the first position. Students will often think that when counting for length they should also start at 0. That’s not the case. Think of length like you’re counting on your fingers.

Let’s look at some code.

System.out.println("Hello, my name is Bob".length()); 

The first line prints 5 because there are 5 characters in the string Hello. They are in positions 0 through 4, but that’s still 5 characters.

The second line prints 0 because it’s an empty string. Still a string, just nothing in it.

And the last prints 21. Notice that spaces and commas count towards the length. Anything between the quotes counts. It doesn’t have to be a letter.

length() and if statements

We haven’t talked about if statements during this series, so don’t worry too much if this looks a bit foreign.

We’re going to use length to make decisions based on how many characters there are in a string.

String s = "Howdy There";
if (s.length() < 5) {
   System.out.println("It's a short string");
else {
   System.out.println("It's a long string");

Since length returns an integer we can compare that value to other values like 5 and 10 in the code above.

length() and loops

More often than ifs you’ll probably use the length method to control loops to look at individual characters. We’re also going to use the substring method which we’ll talk more about in future posts.

String s = "Hello";
for (int i=0; i<s.length(); i++) {
   String ch = s.substring(i, i+1);

What this does is print out each character in Hello on separate lines. Again, we’ll talk about substring a bit later so don’t worry too much now.

In this series

A quick, short introduction to strings in Java.
You can't always work with string literals. You need variables.
Concatenation is the fancy word for combining multiple strings.
Built in method to see if two strings are the same.
Need to know how many characters are in a string? There's a method for that.
indexOf / lastIndexOf
CompSci.rocks Newsletter

Want to stay in touch and keep up to date with the latest posts @ CompSci.rocks?

Leave a Reply

Your email address will not be published. Required fields are marked *