怎么不同?
String a = "ok"和 
String a = new String("ok")
不都是生成一個字符串對象嗎?只是
String a = "ok";
String b = "ok";
a,b不同﹐它們是兩個對象﹐不過由於JVM的內存優化﹐實際上開始時兩個對象都是指向一塊內存區域﹐只是在使用時再復製出一塊新的內存來

解决方案 »

  1.   


    一样吗?不一样,不信你试试:
    String a="ok";
    String b=new String("ok");
    if(a==b)
    {
      out.println("ok");
    }
    else
    {
      out.println("fail");
    }
    或则
    if(a.equals(b))
    {
      out.println("ok");
    }
    else
    {
      out.println("fail");
    }
      

  2.   

    用第一种方法声明时,a位置在内存堆栈中,意味着是原语类型;超出作用域后即丢失。 第二种声明,a位置在内存堆中,换句话说即是对象类,当a超出作用域后,将由垃圾收集器回收。 
      

  3.   

    同意songuo(变量),把我想说得都说了 用第一种方法声明时,a位置在内存堆栈中,意味着是原语类型;超出作用域后即丢失。 第二种声明,a位置在内存堆中,换句话说即是对象类,当a超出作用域后,将由垃圾收集器回收。 在补充一点,由第二种方法比较符合OOP的思想,但速度比较慢。用第一种方法的速度比较快,
    这是由他们不同的存储方式决定的
      

  4.   

    不好意思﹐不知有此區別﹐但我在java docs上看到以下文字
    "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);
    "
    不知何解
      

  5.   

    String a="ok";
    //String b=new String("ok");
    String b="ok";
    if(a==b)
    {
      out.println("ok");
    }
    else
    {
      out.println("fail");
    }
    中的结果是ok
    这个是为什么?
      

  6.   

    不好意思﹐不知有此區別﹐但我在java docs上看到以下文字
    "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 str1 = "abc";  
    is equivalent to:     
     char data[] = {'a', 'b', 'c'};
     String str2 = new String(data);
    "
    不知何解str1.equals(str2) ///println为true;
    应该这样理解,不知对否
      

  7.   

    String a = "ok"和 
    String b = new String("ok")
    第一种方法中"ok"是一个字符串常量,不是在什么堆栈中,而是在一个常数池中,在执行这句的类加载的时候,就被放到这个常数池中而且保持唯一性,赋值只是把一个句柄变量指向这个常数池中的变量"ok".第二种方法源码如下
    public String(String original) {
      this.count = original.count;
      if (original.value.length > this.count) {
          // The array representing the String is bigger than the new
          // String itself.  Perhaps this constructor is being called
          // in order to trim the baggage, so make a copy of the array.
          this.value = new char[this.count];
          System.arraycopy(original.value, original.offset,
           this.value, 0, this.count);
      } else {
          // The array representing the String is the same
          // size as the String, so no point in making a copy.
          this.value = original.value;
      }
        }
    可以看到,实际上是进行字符串复制,把原来在常数池中的字符串"ok"复制为一个新的对象.赋给对象对象句柄b , a!=b ,,所以这两个句柄是不相同的.
    但是 b.intern()==a.intern();
      

  8.   

    而且在SUN的JDK实现中
    b.intern()==a;