String literals vs String Object in Java

java, string

Solution

The short answer: If you're in any doubt, you don't want `new String("literal here")`. If you need it, you'll know you need it, and why.

The long answer:

Essentially the only time you want to use `new String("literal here")` is if you want to ensure that the resulting string object is not `==` any other string object. Literals get interned automatically; strings created via `new String("literal here")` are not.

So why would you want that? The answer is you almost never would, because `String` instances are immutable, so you don't care if you're sharing a `String` instance with something else. Just about the only scenario I can imagine is if you had an API that accepted a `String` and you wanted to have a flag value other than `null`, and you wanted to check that flag/marker value via `==`, like this:

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
    }
}

...and even then I'd tend to find it a bit suspect and would explore other ways to do it.

Problem

In java String can be created in 2 ways given below - `String foo="Test";` - `String fooobj=new String("Test");` Everywhere it is mentioned about difference between these 2 ways of creating String. I want to know more about What are appropriate scenario's , where we should go for ``` String foo="Test"; ``` And when to go for ``` String fooobj=new String("Test"); ? ```

Original source

Related problems