(1)double類型的陷阱
public class DoubleTest {
/**
* 這個程序可能無法結束運行
*/
@Test
public void test(){
for(double x = 0.1; x != 10.0; x += 0.1){
System.out.println(x);
}
}
/**
* 結果有誤差的
*/
@Test
public void test2(){
System.out.println(2 - 1.1); //0.8999999999999999
}
}
(2)不可變的字符串String
public class StringTest {
@Test
public void test(){
String str1 = "hello";
String str2 = str1.substring(0, 2);
System.out.println("str1:" + str1);
System.out.println("str2:" + str2);
}
}
String str1 = "hello";的工作流程如下:
在字符串共享池new一個“hello”對象,然後str1指向“hello”這個對象。
str1.substring(0, 2);的工作流程如下:
在字符串共享池new一個“he”對象,然後str2指向“he”這個對象。
所以,str1並沒有發生改變。
(3)空串和null串
<span style="white-space:pre"> </span>@Test
<span style="white-space:pre"> </span>public void test2(){
<span style="white-space:pre"> </span>String emptyStr = "";
<span style="white-space:pre"> </span>String nullStr = null;
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>//emptyStr是一個字符串引用,指像一個""空字符串(包含0個字符)
<span style="white-space:pre"> </span>if(emptyStr.isEmpty()){
<span style="white-space:pre"> </span>System.out.println("emptyStr是一個空串");
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>//nullStr是一個字符串引用,指向null
<span style="white-space:pre"> </span>if(nullStr == null){
<span style="white-space:pre"> </span>System.out.println("nullStr是一個null對象");
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>//會報空指針異常
<span style="white-space:pre"> </span>if(nullStr.isEmpty()){
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
(4)長度爲0的數組
@Test
public void test(){
int[] array = new int[0];
System.out.println(array.length); //0
}
array是一個數組對象,長度爲0