天天看點

Java中 String s = new String("java265.com")建立了幾個對象呢

String s = new String("java265.com")
  以上代碼運作的将會在字元串池中建立一個“java265.com”
  當我們運作new String時,将字元串池中的字元串複制到堆中,将堆的位址執行s
--------------------------------------------------------------------------------
 通過上面的分析,我們可以得知,以上的操作
 在jvm中最多産生兩個對象(因為java265.com存在字元串池中時,隻會建立一個對象)      
package com.java265.other;
public class Test {
  public static void main(String[] args) throws Exception {
    String s1 = new String("java265.com");
    String s2 = new String("java265.com");
    if (s1 == s2) {
      System.out.println("堆中為相同一個對象");
    } else {
      System.out.println("堆中存在二個對象");
    }
  }
}
-------運作以上代碼,将輸出以下資訊------
堆中存在二個對象