请参考以下文档: The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example: String str = "abc";
is equivalent to: char data[] = {'a', 'b', 'c'}; String str = new String(data);
String a = "ABC"; String b = "ABC"; a == b --> true a.equals(b) --> trueString a = new String("ABC"); String b = new String("ABC"); a == b --> false a.equals(b) --> true第一个之所以是true是java优化的问题 它跟这个是等价的 String a = "ABC"; String b = a;
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
这个特性只是为了方便,Java给的方便你还有意见啊!
我的理解是 创建对象用如下语法:类名 对象名 = new 构造器那么我就有了一个概念,即创建对象的语法
而 String对象居然是这样的 String 对象名="test";
我就不理解了,除非java规定 String对象创建的语法与与众不同还是不明白啊,那位大哥能给我指点迷津?
"test" 应该是一个匿名对象
而java的特点是自动回收,String str申明了一个对象,而这个对象引用了那个匿名对象,从而使用str就相当于使用了"test"
记得就行了
可能你要到sun公司去问问明白了.
用new String("")来定义的String是新开一块内存区域来存储内容
(赋值给变量),
而直接用=""就是先从一个什么存储空间里(好像叫堆吧)找,
找到了,就把变量指向那个值,
没有的话就在那个存储空间里建这么一个值,然后赋给变量!说的不对就算我说梦话吧!:)good luck
String mystr = new String("test"); //对象分配,再程序中实现。
String是一个特殊对象,你可以通过new来实例化,也可以匿名实例化。
但是匿名实例化的效率比new实例化的效率还要高,你可以试试。
根本就没有为mystr创建对象吧!
它应该相当于
String temp = new String("test");
String mystr = mystr;其中temp是JVM自动创建的
mystr只是一个引用而已类似于C里面:char * p = "hi!";
String mystr = "test"; 不是定义了一个字符串变量吗?
这个变量和对象有什么区别?
String b = "ABC";
a == b --> true
a.equals(b) --> trueString a = new String("ABC");
String b = new String("ABC");
a == b --> false
a.equals(b) --> true第一个之所以是true是java优化的问题
它跟这个是等价的
String a = "ABC";
String b = a;