基礎知識
1. 數值的進制
二進制數 前綴 0b | 0B
八進制數 前綴 0
十進制數 無前綴
十六進制數 前綴 0x | 0X
System.out.println("二進制數 1000:"+0b1000); //二進制數 1000:8
System.out.println("八進制數 1000:"+01000); //八進制數 1000:512
System.out.println("十進制數 1000:"+1000); //十進制數 1000:1000
System.out.println("十六進制數 1000:"+0x1000); //十六進制數 1000:4096
2. 轉義序列符\u可以出現在字符常量或字符串的引號之外。
int[] u = new int\u005B3\u005D; //合法 相當於 int[] u = new int[3];
3. 常量的使用
//方法中聲明則僅能在聲明的方法中使用
final int CIMETHOD = 1;
//類中方法外聲明則可以在多個方法,多個類中使用;稱之爲類常量
static final int PCOMETHODICLASS = 2;
public static final int PCOMETHODICLASS = 2;
//類中方法外聲明則僅可以在這個類的多個方法中使用
private static final int PCOMETHODICLASS = 2;
4. String類對象爲不可變字符串
5. 不要用“==”檢測兩個字符串是否相等,這個運算符只能夠確定兩個字符串是否放置在同一個位置上,要比較兩個字符串是否相當用equals()。
6. 有些時候,需要由較短的字符串構建字符串,例如,按鍵或來自文件中的單詞。採用字符串連接的方式達到此目的效率比較低。每次連接字符串,都會構建一個 新的String對象,既耗時,又浪費空間。使用StringBuilder類就可以避免這個問題的發生。
//StringBuilder Nicholas8false
public static void stringBuilderTest() {
StringBuilder sb = new StringBuilder();
sb.append("Nicholas");
sb.append(8);
sb.append(false);
System.out.println(sb.toString());
}
7. 格式化字符串
//格式化輸出
//My name is Hzf and my age is 23
//My name is Nicholas and my age is 23
public static void stringFormat() {
String info = String.format("My name is %s and my age is %d","Hzf",23);
System.out.println(info);
System.out.printf("My name is %s and my age is %d","Nicholas",23);
}
8. 在循環條件的判定中,檢測兩個浮點數是否相等需要格外小心,由於舍入誤差可能造成死循環。
9. 帶標籤的break語句,標籤必須放在希望跳出的最外層循環之前,並且必須緊跟一個冒號。有些類似C++中的goto語句。
//帶標籤的break語句
//0
//0G
public static void breakWithLabel() {
System.out.println();
label:
for (int i = 0; i < 3; i++) {
System.out.println(i+" ");
for (int j = 0; j < 3; j++) {
if ( j == 1 ) {
break label;
}
System.out.print(j+"G ");
}
System.out.println();
}
}
10. java.math中的BigInteger和BigDecimal可以處理包含任意長度數字序列的數值,實現了任意精度的運算。不能使用算數運算符處理大數值,需要使用大數值類的add,multiply等方法。
11. Arrays.toString()可簡單實現數組打印
//數組元素的快速打印 [0, 1, 2, 3, 4]
public static void arrayDisplay() {
int[] a = new int[5];
for(int i = 0 ; i < 5 ; i++) {
a[i] = i ;
}
System.out.println(Arrays.toString(a));
}
//想要快速打印二維數組,可用
//System.out.println(Arrays.deepToString(a));
12. 在Java中,允許數組長度爲0。在編寫一個結果爲數組的方法時,如果碰巧結果爲空,則這種語法形式就顯得非常有用。此時可以創建一個長度爲0的數組:new elementType [0]
學習整理自《Java 核心技術 卷一 基礎知識》