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
- Learn: Declaring Strings
- Learn: Constructing a String
- Learn: Introduction to String Indexing
- Learn: Comparing Two String Objects Using compareTo Methods
- Learn: Comparing String Objects with equals Methods
- Learn: Obtaining Substrings from a String Object
- Learn: Using the split method on a String
- Practice: Evaluating Expressions that use the String Class
- Practice: Writing Code Using the String Class
- FRQ Practice: AP Computer Science A FRQ 1 Formatting Words
- FRQ Practice: AP Computer Science A FRQ 1 Sentence Analysis