String literals and string objects in Java
In Java, string can be created in the following two ways
>String foo = "test"; > String fooobj = new String(“Test”);
Here, we mentioned the difference between the two methods of creating strings I want to know more about what is the appropriate scene and where we should go
String foo="Test";
What time do you go?
String fooobj=new String("Test"); ?
Solution
Short answer: if you have any questions, you don't need a new string ("literal here") If you need it, you will know why you need it
The answer is long:
Basically, the only time you want to use a new string ("literal here") is to make sure that the resulting string object is not = = any other string object Text automatically gets connected; The string created through new string ("literal here") is not
So why are you doing this? The answer is that you will almost never, because string instances are immutable, so you don't care if you share a string instance with others Almost the only situation I can imagine is that if you have an API that accepts a string and you want a non null flag value, you want to check that flag / tag value through = = as follows:
public static final String MARKER = new String("Marker"); public void someFictionalMethod(String arg) { if (arg == MARKER) { // Take action on the marker } else { // Take action on the string } }
... even so, I tend to find it a little skeptical and explore other ways to do it