Create and assign simple strings of characters - Example 4
Snippet: Create, Assign and Concatenate Simple Strings of Characters
Explanation
This snippet shows how to concatenate a string and reassign the result to the same variable. The variable message starts with the value "Hello". Then, message + " World" creates a new string "Hello World", and the result is assigned back to message.
After the reassignment, message holds "Hello World". The original "Hello" string is not modified — strings in Java are immutable. The variable simply now points to a new string value.
What You Can Do
Try concatenating more words — can you build a full sentence step by step, reassigning message each time?
You can also try using the += shorthand: message += " World" does exactly the same thing as message = message + " World". Does the output change?
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