Create and assign simple strings of characters - Example 3
Snippet: Create and assign simple strings of characters using new String()
Explanation
This snippet introduces the new String() constructor as an alternative way to create a String. The variable message2 is created using new String(message1), which produces a new string with the same characters as message1.
Then, message1 is reassigned using new String("World"). When both variables are printed, message2 still holds "Hello" — just like with a plain assignment, reassigning message1 has no effect on message2. The new String() constructor creates an independent copy of the string's characters.
What You Can Do
Try comparing the two ways of creating a string: String s1 = "Hello" and String s2 = new String("Hello"). Do they print the same value?
They might behave differently when compared with == versus .equals() — can you find out why?
You can also try passing a string literal directly to the constructor, like new String("World"), versus passing a variable. Does it make a difference in the output?
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