public static void main(String[] args) { Integer i1 = new Integer(1); Integer i2 = new Integer(1); // i1,i2分別位於堆中不同的記憶體空間 System.out.println("i1 == i2:
public static void main(String[] args) { Integer i1 = new Integer(1); Integer i2 = new Integer(1); // i1,i2分別位於堆中不同的記憶體空間 System.out.println("i1 == i2:" + (i1 == i2));// 輸出false String s1 = "china"; String s2 = "china"; String ss1 = new String("china"); String ss2 = new String("china"); System.out.println("s1 == s2:" + (s1 == s2)); System.out.println("ss1 == ss2" + (ss1 == ss2)); System.out.println("s1 == ss2" + (s1 == ss2)); // 利用Java反射機制改變string的值 Field f = null; Field f1 = null; try { f = s1.getClass().getDeclaredField("value"); f1 = ss1.getClass().getDeclaredField("value"); } catch (NoSuchFieldException e) { e.printStackTrace(); } f.setAccessible(true); f1.setAccessible(true); try { f.set(s1, new char[] { 'c', 'h', 'i', 'n', 'b' }); f1.set(ss1, new char[] { 'c', 'h', 'i', 'n', 'b' }); } catch (Exception e) { e.printStackTrace(); } System.out.println("改變後的s1的值:" + s1); System.out.println("s2的值是:" + s2); System.out.println("ss1的值是:" + ss1); System.out.println("s1 == s2:" + (s1 == s2)); System.out.println("ss1 == ss2" + (ss1 == ss2)); System.out.println("s1 == ss2" + (s1 == ss2)); System.out.println("============分割線=================="); System.out.println("改變後的ss1的值:" + ss1); System.out.println("ss2的值是:" + ss2); }
列印的結果:
i1 == i2:false
s1 == s2:true
ss1 == ss2false
s1 == ss2false
改變後的s1的值:chinb
s2的值是:chinb
ss1的值是:chinb
s1 == s2:true
ss1 == ss2false
s1 == ss2false
============分割線==================
改變後的ss1的值:chinb
ss2的值是:china