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

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>