當你看見這個標題的時候,你可能會下意識的去想一下,這兩種方式到底有什么樣的區別呢?
且看下面的demo,自然便區分開了
1 /** 2 * 3 */ 4 package com.b510.test; 5 6 /** 7 * Problem: 8 * 對於String對象,可以使用"="賦值,也可以使用"new"關鍵字賦值,兩種方式有什么區別? 9 * 也即: 10 * String testStrA = "abc"; 11 * String testStrB = new String("abc"); 12 * 13 * @author Jone Hongten 14 * @create date:2013-10-31 15 * @version 1.0 16 */ 17 public class StringTest { 18 19 public static void main(String[] args) { 20 String testStrA = "abc"; 21 String testStrB = new String("abc"); 22 System.out.println("testStrA == testStrB ? " + (testStrA == testStrB ? true : false)); 23 24 String testStrC = "abc"; 25 System.out.println("testStrA == testStrC ? " + (testStrA == testStrC ? true : false)); 26 27 String testStrD = "ab"; 28 String testStrE = "c"; 29 String testStrF = testStrD + testStrE; 30 System.out.println("testStrA == testStrF ? " + (testStrA == tsetStrF ? true : false)); 31 } 32 }
運行效果:
testStrA == testStrB ? false testStrA == testStrC ? true testStrA == testStrF ? false
我們來分析一下,為什么會出現這樣的結果:
首先我們要明白的是
1 String testStrA = "abc";
這樣的代碼,可能會創建一個對象或者不會創建對象:這里會出現一個名詞“字符串實例池”
實例池中存在字符串:
這個名詞很形象,在這個字符串實例池中,存放着很多字符串,可能包含有字符串:"abc",所以
在這種情況下面,上面的語句是不會創建對象的,而是直接引用池子中的字符串:"abc";
實例池中不存在字符串:
如果字符串"abc"在實例池中並不存在,那么這時,就會初始化一個字符串:"abc",即創建
一個字符串對象:"abc",並且會把創建好的字符串放入到"字符串實例池"中。
1 String testStrB = new String("abc");
對於關鍵字:new ,即會產生新的對象,也就是說,每次都會產生新的字符串對象
這樣,對於第一個結果:
testStrA == testStrB ? false
我們就知道了,原來是這樣的。
而對於第二個結果:
testStrA == testStrC ? true
只要我們對"字符串實例池"有一個印象,這也是不難理解的。
最后是第三個結果:
testStrA == testStrF ? false
這個要稍微難理解一些。
1 String testStrD = "ab"; 2 String testStrE = "c"; 3 String testStrF = testStrD + testStrE;
字符串testStrD和testStrE都是字符串常量,所以他們在代碼編譯的時期就已經是確定好的了,
但是對testStrF來說,他的值是testStrD和testStrE的引用,所以不會在編譯時期確定,實際上
testStrF類似於新建了一個對象出來,然后把所創建的對象的引用賦值給了testStrF。
所以出現第三個結果也是情理之中的事情...
========================================================
More reading,and english is important.
I'm Hongten
大哥哥大姐姐,覺得有用打賞點哦!多多少少沒關系,一分也是對我的支持和鼓勵。謝謝。
Hongten博客排名在100名以內。粉絲過千。
Hongten出品,必是精品。
E | hongtenzone@foxmail.com B | http://www.cnblogs.com/hongten
========================================================