永中首页 | 产品聚焦 | 销售渠道 | 服务支持 | 教育专栏 | 二次开发 | 在线订购 | 产品注册 | 免费下载 | 新闻中心 | 关于永中 | 永中未来星
发新话题
打印

请教一个关于String的问题

请教一个关于String的问题

public class Test{
   public static void main(String[]args ){
       String a="asdf";
       String b="asdf";
       System.out.println(a==b);
       System.out.println(a!=b);
   }
}
运行的结果是:
true
false

而我将程序中的String a="asdf";    String b="asdf";  
改为  Sring a=new String("asdf"); String b=new String("asdf");

运行的结果是:
false
true
修改后结果的原因是a,b的引用是不同的。
但我在书上看到String a="asdf";和String a=new String("asdf");是一样的。
但上面的结果明显说明是不同的。
谁能告诉我String a="asdf";到底是什么意思?
和String a=new String("asdf");有什么不同?万分感谢!

TOP

怎么没人回答我的问题啊?

TOP

如果你是直接定义,则用的是同一个对象,如果显式的new String,则是生成一个新的String对象。

TOP

对,String a="asdf";        String b="asdf";这样的话a,b是同一个对象‘asdf‘的引用,所以a==b;而Sring a=new String("asdf"); String b=new String("asdf");创建了两个对象,a,b是两个对象的不同引用。只不过被引用对象的值是相等的而已。
When Programming ,There is no world....

TOP

看看java采用了优化机制

TOP

引用:
Originally posted by anyplace at 2004-10-7 08:59 AM:
看来java采用了优化机制
我测试了一下,就算是在不同对象中定义相同的字符串,他们还是相等的。这个对象共享机制不错呀,值得参考!

TOP

JVM规范中有写这种情况, 常量会被放入一个成为常量池的内存空间, 也就是说相同的常量是不能出现两次的, 所以在程序中定义的两个常量会指向同一块内存空间,这是虚拟机对程序做的优化。 但是用new的话,就不能当常量对待了,所以是指向两个不同的内存空间。

[ Last edited by hubin on 2004-10-7 at 22:07 ]

TOP

大家要理解常量池

Let’s look at a couple of examples of how a String might be created, and let’s further assume that no other String objects exist in the pool:
1 – String s = "abc"; // creates one String object and one reference
// variable
In this simple case, “abc” will go in the pool and s will refer to it.
2 – String s = new String("abc"); // creates two objects, and one
// reference variable
In this case, because we used the new keyword, Java will create a new String object in normal (nonpool) memory, and s will refer to it. In addition, the literal “abc” will be placed in the pool.
[color=blue][b]伟大的民族是教育出来的![/b][/color]

TOP

或者用javap 来反编译.class文件来分析。
[color=blue][b]伟大的民族是教育出来的![/b][/color]

TOP

发新话题