Getting the Length of an Empty String and Concatenate It - Example 4
Snippet: Getting the Length of an Empty String and Concatenate It
Explanation
This snippet introduces the empty string "" — a valid String that contains no characters. Calling length() on it returns 0, which confirms that it exists but holds nothing.
After concatenating "Hello" to it, message becomes "Hello" with a length of 5. This is a common pattern for building a string incrementally, starting from an empty string and adding to it step by step.
What You Can Do
Try concatenating more strings to message in additional steps, updating length each time. Can you build a full sentence this way?
You can also try checking whether an empty string "" is the same as not having a string at all. What do you think would happen if message were null instead of ""? Would length() still work?
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