Getting the Length of Several Strings
Snippet: Getting the Length of Several Strings and compare their lengths
Explanation
This snippet extends the use of length() to multiple String variables. Each string has its own length() call, and the result is stored in a separate int variable.
"Hello" has 5 characters, so length1 is 5. "World!" has 6 characters — the exclamation mark counts too — so length2 is 6. Each variable independently tracks the length of its own string.
What You Can Do
Try adding a third string and computing its length. What happens if the string contains spaces — does length() count them?
You can also try printing the sum of the two lengths: length1 + length2. Does it match the length of the concatenated string message1 + message2?
Run it and observe the output!
Last update: May 1, 2026