java String 的+操作導致的問題

來源:互聯網
上載者:User

標籤:code   static   abstract   key   build   turn   virt   reg   spec   

 

不說別的先看代碼:

結果如下:

很好奇為什麼String對象的null加上了""就等於"null"字串了,先給點資料看看:

這個是我找的一個人部落格上的,null不是任何對象的類型,那麼這個到底是怎麼實現的呢?

機制的我又找到了一點資料:

L0 LINENUMBER 27 L0 ACONST_NULL ASTORE 1L1 LINENUMBER 28 L1 NEW java/lang/StringBuilder DUP INVOKESPECIAL java/lang/StringBuilder.<init> ()V ALOAD 1 INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder; LDC "!" INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder; INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String; ASTORE 1L2 LINENUMBER 29 L2 GETSTATIC java/lang/System.out : Ljava/io/PrintStream; ALOAD 1 INVOKEVIRTUAL java/io/PrintStream.print (Ljava/lang/String;)
這個是我找到的一個位元組碼的,就是java編譯器對於+這個操作的最佳化,算了,直接說吧:
當我們在程式中使用了字串相加的話,編譯器就會對這個進行最佳化,先執行個體化一個stringbuilder對象,然後把相加的字串一個個的apend進去,
然後就.tostring了,轉換成字串了。其中對於null會轉換成null字串來接收他。原始碼如下:
/針對 String 對象public AbstractStringBuilder append(String str) { if (str == null) return appendNull(); int len = str.length(); ensureCapacityInternal(count + len); str.getChars(0, len, value, count); count += len; return this;}//針對非 String 對象public AbstractStringBuilder append(Object obj) { return append(String.valueOf(obj));}private AbstractStringBuilder appendNull() { int c = count; ensureCapacityInternal(c + 4); final char[] value = this.value; value[c++] = ‘n‘; value[c++] = ‘u‘; value[c++] = ‘l‘; value[c++] = ‘l‘; count = c; return this;}


簡單易懂,下面給個demo看看:

結果如下:

 

 


 
 

 

java String 的+操作導致的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.