String literals vs String Object in Java

In java, a String can be created in two ways, given below.

  • String foo="Test";
  • String fooobj=new String("Test");

Everywhere is mentioned the difference between the two ways to create a String. I want to learn more about What is the appropriate scenario, where should we go for

  String foo="Test";

And when to go after

 String fooobj=new String("Test");  ?
+3
source share
6 answers

Short answer: if in doubt, you do not want new String("literal here"). If you need it, you will find out what you need and why.

Long answer:

, , new String("literal here"), , == . ; , new String("literal here"), .

? , String , , String - . , , - API, String, , null, / ==, :

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

... .

+11

String

String fooobj = new String("Test");

, . String fooobj = "Test";.

String . , String . .

+7

new String(). , , . String s = "aaa", , JVM, , - .

+3

, .

, , String , ?

, .

0

String .

String s = "abc";// String "abc" , s .

String s = new String ( "abc" );// , , Java String ( ) , s . , "abc" .

0

; . String . String , . :

     String str = "abc";

:

     String str = new String("abc");

,

-2

All Articles