老司机也晕车--java字符串String晕车之旅
首先聲明,有暈車經歷的司機請自備藥物,String也可能讓你懷疑人生!
?
第一道 開胃菜
請聽題!第一道題:
String hello="hello world!";String hello1=new String("hello world!");System.out.println(hello==hello1);System.out.println(hello.equals(hello1));?
?
提示: ==是比較兩個對象引用是否正好引用到了相同的對象。
?
那么公布答案吧
falsetrue
旁白:
肯定不過癮吧,那就再來。
第二道 湯
String hello="hello world!";String hello2="hello world!";System.out.println(hello==hello2);System.out.println(hello.equals(hello2));?
?
掃地僧看不下去了
?
truetrue
旁邊:
兩個String類型的常量表達式,如果標明的是相同的字符序列,那么它們就用相同的對象引用來表示。
第三道 副菜
String hello="hello world!"; String append="hello"+" world!";System.out.println(hello==append);System.out.println(hello.equals(append));?
?
那就公布答案
truetrue
旁邊:
兩個String類型的常量表達式,如果標明的是相同的字符序列,那么它們就用相同的對象引用來表示。
第四道 主菜
final String pig = "length: 10";final String dog = "length: " + pig.length();System.out.println(pig==dog);System.out.println(pig.equals(dog));?
?
不敢說了,還是公布答案吧
falsetrue
?
官方資料中有這么一段話:
Strings concatenated from constant expressions (§15.28) are computed at compile time and then treated as if they were literals.Strings computed by concatenation at run time are newly created and therefore distinct.
?
翻譯一下:
>通過常量表達式運算得到的字符串是在編譯時計算得出的,并且之后會將其當作字符串常量對待.
>在運行時通過連接運算得到的字符串是新創建的,因此要區別對待。
看黑色重點標注。
第五道 蔬菜類菜肴
final String pig = "length: 10";final String dog = ("length: " + pig.length()).intern();System.out.println(pig==dog);System.out.println(pig.equals(dog));?
先看答案吧
truetrue
?
旁邊:
可以通過顯示的限定運算得到的字符串為字符串常量,String.intern方法可以"限定"
第六道 甜品
final String pig = "length: 10";final String dog = "length: " + pig.length();System.out. println("Animals are equal: "+ pig == dog);System.out.println("Animals are equal: "+ pig .equals(dog));?
大家已經迫不及待了,先看答案
falseAnimals are equal: true
?
如果你想一下操作符的優先級就明白了,“+”優先級高于“==”
?
第七道 咖啡、茶
?
看大家暈車嚴重,那就不出題目了
?
通過上面的教訓,在比較對象引用時,應該優先使用equals 方法而不是 == 操作符,除非需要比較的是對象的標識而不是對象的值。
參考資料
【1】https://docs.oracle.com/javase/specs/jls/se12/html/jls-3.html#jls-3.10.5
【2】https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
轉載于:https://www.cnblogs.com/davidwang456/p/11459740.html
總結
以上是生活随笔為你收集整理的老司机也晕车--java字符串String晕车之旅的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: tomcat架构分析 (Session管
- 下一篇: Java 编程语言中很少被人了解的特性-