學習筆記之《Java核心技術卷I》---- 第三章 Java的基本程式設計結構
阿新 • • 發佈:2018-12-15
- Java中沒unsigned關鍵字
- int Math.round(float a) long Math.round(double a)
- &&、||:短路操作 &、|:非短路操作
- 列舉型別必須放在放在函式之外定義
- Java String中的字元不能修改修改,String類物件為不可變字串
-
String greeting = "hello"; System.out.println(greeting == "hello");//true System.out.println(greeting.substring(0,4) == "hell");//false System.out.println(greeting.substring(0,5) == "hello");//true System.out.println("he" + "l" == "hel");//true
substring原始碼:
public String substring(int beginIndex, int endIndex) { if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } if (endIndex > value.length) { throw new StringIndexOutOfBoundsException(endIndex); } int subLen = endIndex - beginIndex; if (subLen < 0) { throw new StringIndexOutOfBoundsException(subLen); } return ((beginIndex == 0) && (endIndex == value.length)) ? this : new String(value, beginIndex, subLen); }
在原始碼中,可以看出,如果需要返回的子串不是原字串本身,就得返回一個新物件(此時該物件通過new關鍵字建立,存在於堆之上);而字面量"hell"存在於棧之上,兩者的地址不同;通過"+"得到的新物件也是存在於棧之上
- Java的八大基本資料型別:byte、short、int、long、float、double、char、boolean
- 對於Java八大基本資料型別來說,無論其變數值是通過字面量直接賦值而得還是通過關鍵字new而得,該物件都是存放於棧之上
char c = 'h';
char c1 = new Character('h');
System.out.println(c == c1);//true
- StringBuilder在單執行緒中比StringBuffer更具優勢
- String、StringBuffer、StringBuilder內部都是使用字元陣列儲存變數的值
- BigInteger與BigDecimal之間無法進行運算
-
int[] s = {1,23,4};//相當於int[] s = new int[]{1,23,4} int[] a = {1,23,4};//相當於int[] a = new int[]{1,23,4} System.out.println(s == a);//false
- 棧中一般存放八大基本資料型別的物件(字面量)、通過字面量賦值的字串以及引用變數,堆中一般存放通過關鍵字new而得到的非八大基本資料型別的物件
- Arrays.copyOf(original, newLength) //陣列複製函式。第一個引數為原陣列,第二個引數為新陣列的長度 。在該函式的最內部實現中,會建立一個新的陣列copy,用於儲存新陣列的元素,再返回copy,使得新陣列與copy指向堆中的同一物件。若newLength大於original.length,則在新陣列中,索引在original.length及之後的陣列元素值為0或false
public static <T> T[] copyOf(T[] original, int newLength) {
return (T[]) copyOf(original, newLength, original.getClass());
}
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
- Java中提供了直接使用{}建立一維陣列和二維陣列的方法
int[][] aa = {{1,23,4},{4,5,6}};
int[] a1 = {1,2,3};
- Arrays.deepToString()
int[][] aa = {{1,23,4},{4,5,6}};
System.out.println(Arrays.deepToString(aa));//[[1, 23, 4], [4, 5, 6]]
- Java建立不規則陣列
int[][] a = new int[5][];//此時a[i] = null,i=0,1,2,3,4
for (int i = 0; i < a.length; i++) {
a[i] = new int[i + 1];//此時,a[i]中的每個元素都是0
for(int j = 0;j <= i;j++) {
a[i][j] = j;
}
}
System.out.println(Arrays.deepToString(a));