日期:2014-05-20  浏览次数:20645 次

分享:一道BT试题
近日,在下到某公司面试,满怀信心的我重重的载在那份BT试题上。
    其中一道:
    以下code生成几个String对象
    String   a= "abc ";
    String   b= "abc ";
    String   c=new   String( "abc ");
    String   d=c.intern();

    当时在下毫不忧郁的选3。
    后来在Java   Language   Specification/CHAPTER   3/Lexical   Structure发现这样一个测试代码,知道错了。

    package   testPackage;
    class   Test   {
public   static   void   main(String[]   args)   {
    String   hello   =   "Hello ",   lo   =   "lo ";
    System.out.print((hello   ==   "Hello ")   +   "   ");
    System.out.print((Other.hello   ==   hello)   +   "   ");
    System.out.print((other.Other.hello   ==   hello)+ " ");
    System.out.print((hello   ==   ( "Hel "+ "lo "))   +   "   ");
    System.out.print((hello   ==   ( "Hel "+lo))   +   "   ");
    System.out.println(hello   ==   ( "Hel "+lo).intern());
}
    }
      class   Other   {   static   String   hello   =   "Hello ";   }
   
    学海无崖,顿感羞愧,特此分享。

------解决方案--------------------
two?
------解决方案--------------------
2个
常量池中一个,堆中一个。
------解决方案--------------------
我发现这个错误很多人犯。为什么会这样呢?难道老师不好?或者没看到好书?
------解决方案--------------------
学习了.谢谢教导
------解决方案--------------------
我怎么感觉是创建了一个对象呢,难道 "String d=c.intern(); "也是对象的创建,没怎么见过.
------解决方案--------------------
to:toploveall
String b= "abc ";
String c=new String( "abc ");
这两句分别创建两个
------解决方案--------------------
顶.
------解决方案--------------------
String a= "abc ";
String b= "abc ";
String c=new String( "abc ");
String d=c.intern();

其中abd属于常量池,c属于堆
------解决方案--------------------
唉,还真不知道。
------解决方案--------------------
String s = new String( "abc ");创建了几个String Object?
引用变量与对象的区别;
字符串文字 "abc "是一个String对象;
文字池(pool of literal strings)和堆(heap)中的字符串对象。

一、引用变量与对象:除了一些早期的Java书籍和现在的垃圾书籍,人们都可以从中比较清楚地学习到两者的区别。
A aa;
这个语句声明一个类A的引用变量aa[我们常常称之为句柄],而对象一般通过new创建。所以题目中s仅仅是一个引用变量,它不是对象。

二、Java中所有的字符串文字[字符串常量]都是一个String的对象。有人[特别是C程序员]在一些场合喜欢把字符串 "当作/看成 "字符数组,
这也没有办法,因为字符串与字符数组存在一些内在的联系。事实上,它与字符数组是两种完全不同的对象。

System.out.println( "Hello ".length());
char[] cc={ 'H ', 'i '};
System.out.println(cc.length);

三、字符串对象的创建:
由于字符串对象的大量使用(它是一个对象,一般而言对象总是在heap分配内存),Java中为了节省内存空间和运行时间