Skip Top Navigation Bar

Getting the Length of a String - Example 1

Snippet: Getting the Length of a String

Explanation

This snippet shows how to use the length() method to get the number of characters in a String. The variable message is first set to "Hello", which has 5 characters — so length() returns 5.

Then message is reassigned to "World!", which has 6 characters including the exclamation mark. Calling length() again now returns 6. Notice that length is a plain int variable that needs to be updated manually — it does not automatically track changes to message.

What You Can Do

Try calling length() on an empty string "". What do you expect to get?

You can also try computing the length of a concatenated string directly, like ("Hello" + " World!").length(). Does the result match what you would expect?

Run it and observe the output!

Example List

Additional Resources