When creating a String in Java, what is the difference between these two:
String test = new String();
test = "foo";
and
String test = "foo";
When do I need to use the keyword new? Or are these two basically the same and they both create a new String object?
Java String is, however, special. Unlike an ordinary class: String is associated with string literal in the form of double-quoted texts such as " hello, world ". You can assign a string literal directly into a String variable, instead of calling the constructor to create a String instance.
In Java, a string is an object that represents a number of character values. Each letter in the string is a separate character value that makes up the Java string object. Characters in Java are represented by the char class. Users can write an array of char values that will mean the same thing as a string.
In the first snippet, you create a new empty string, and then immediately overwrite it with a string literal. The new string you created is lost, and will eventually be garbage-collected.
Creating it is pointless, and you should just use the second snippet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With