提问初始化问题

oDon 2006-03-06 10:51:37
String s= {"123141231"}

String s= new String("123141231")
什么区别?
...全文
89 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
oDon 2006-03-07
  • 打赏
  • 举报
回复
学习了,因为自学Java很多基础都不牢固,谢谢前辈!
chg2008 2006-03-07
  • 打赏
  • 举报
回复
都说很详细啊啊
hongke1490 2006-03-07
  • 打赏
  • 举报
回复
String s= new String("123141231");
强制产生一个新对象
String s="123141231";
s会引用内存中已有的字符串
例如
String s1=new String("abc");
String s2=new String("abc");

s1!=s2,s1.equals(s2)=true;

String s1="abc";
String s2="abc";

s1==s2,s1.equals(s2)=true;
wangx1949 2006-03-07
  • 打赏
  • 举报
回复
第一个是一个对象
第二个是两个对象
很明显
cdredfox 2006-03-07
  • 打赏
  • 举报
回复
String s= new String("123141231")
好像也是一个对象吧,
 在JAVA中,相同的字符对象不是放在HEAD中的吗??
ogmios 2006-03-07
  • 打赏
  • 举报
回复
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"

//Java programming language code
String s1 = "hello";
String s2 = s1;
s1 += " world";
System.out.println(s1 + "\n" + s2);
//s1 = "hello world" and s2 = "hello"

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.

source: http://java.sun.com/docs/books/tutorial/java/data/stringsAndJavac.html
aaa2003gf 2006-03-06
  • 打赏
  • 举报
回复
String s= "123141231" 一个对象
String s= new String("123141231") 两个对象
晨星 2006-03-06
  • 打赏
  • 举报
回复
String s= {"123141231"}
可以吗?
应该是
String s= "123141231";
吧?

首先,“s”是个变量名,即“引用”,"123141231"则表示一个字符串常量。而常量本身也能代表一个运行时的对象。所以
String s = "123141231";
只是让变量s引用到一个字符串对象(即常量"123141231"所代表的那个),而“String s = new String("123141231")”,则是利用"123141231"作参数,首先构造一个新的String对象,然后让s引用到它。
所以后者比前者多产生了一个冗余对象。

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧