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
- 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