Skip Top Navigation Bar

Getting the Length of Several Strings and Concatenate Them - Example 3

Snippet: Getting the Length of Several Strings and Concatenate Them

Explanation

This snippet combines concatenation and length() to show how the length of a string changes after reassignment. The variable message starts as "Hello" with a length of 5. After concatenating " World!", it becomes "Hello World!" with a length of 12.

Notice that length must be explicitly updated by calling message.length() again — it does not update automatically when message changes. This is an important detail: length is just an int that holds a value at a point in time, not a live connection to the string.

What You Can Do

Try concatenating a third word and printing the length again. Does the length grow as expected?

You can also try computing the length before updating message, but printing it after. Does length reflect the old or new value? This will help you understand when the value of length gets updated.

Run it and observe the output!

Example List

Additional Resources