Because the compiler automatically creates a new String object for every literal string it encounters, you can use a literal string to initialize a String.
String s = "Test";
The above construct is equivalent to, but more efficient than, this one, which ends up creating two Strings instead of one:
String s = new String("Test");
The compiler creates the first string when it encounters the literal string "Test", and the second one when it encounters new String.
source: http://java.sun.com/docs/books/tutorial/java/data/stringsAndJavac.html
Advice: If you are C/C++ programmer be careful with shortcut assignment operator "+=" in Java when you work with Strings!
Why: The shortcut assignment operator += when used with Strings may confuse C and C++ programmers at first. Recall that a += b is equivalent to a = a + b. Let's look at two code
samples written in C++ and the Java programming language:
//C++ code
string* s1 = new string("hello");
string* s2 = s1;
(*s1) += " world";
cout<<*s1<<endl<<*s2<<endl;
return 0;
//s1 = s2 = "hello world"
In the C++ example, the strings s1 and s2 print the same result because they both point to the same address. In the Java programming language, Strings can't be modified, so the + operator must create a new String when "world" is appended to s1.
首先,“s”是个变量名,即“引用”,"123141231"则表示一个字符串常量。而常量本身也能代表一个运行时的对象。所以
String s = "123141231";
只是让变量s引用到一个字符串对象(即常量"123141231"所代表的那个),而“String s = new String("123141231")”,则是利用"123141231"作参数,首先构造一个新的String对象,然后让s引用到它。
所以后者比前者多产生了一个冗余对象。