Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Beginner question regarding Strings

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?

like image 301
itoilet Avatar asked Apr 11 '19 06:04

itoilet


People also ask

What is special about strings in Java?

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.

How does Java consider a string?

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.


1 Answers

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.

like image 169
Mureinik Avatar answered Sep 28 '22 19:09

Mureinik