你的位置:首页 > Java教程

[Java教程]String和常量池值的变化



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