Getting the Length of Several Strings - Example 2
Snippet: Getting the Length of Several Strings
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!
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