Java學習筆記
1 | public class Main { |
Java每一行程式碼都屬於一個class,class都是大寫開頭,例如Main。
main()
每個Java程式都必須要有main(),且一定會被執行。
Java Variables
type variable = value;
例如:String name = "John"
先宣告變項,再assign數值:
1 | int myNum; |
Final Variables
變項的數值不能被覆寫(overwrite)final int myNum = 15;
多個同類型變數同時宣告
int x = 5, y = 6, z = 7;
資料類型
https://www.w3schools.com/java/java_data_types.asp
Casting
primitive資料類型轉為另一種。
Widening Casting (automatically) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> doubleNarrowing Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte
String method
- length()
- toUpperCase(), toLowerCase()
- indexOf()
- concat()
算數方法
- Math.max(x, y), Math.min(x, y)
- Math.sqrt(x)
- Math.abs(x)
- Math.random()
If…Else條件式簡寫
variable = (condiction) ? expressionTrue : expressionFalse;
Switch
1 | switch(expression) { |
while & do/while
差別:do/while至少會運行一次,才檢查condition
while:
1 | while (condition) { |
do/while:
1 | do { |
for-each loop
用來loop陣列(array)
1 | for (type variableName : arrayName) { |
範例:
1 | String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; |
break & continue
- break: 跳出、終止loop
- continue: 跳出當前的loop,但會繼續到下一個
array
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
多維度:int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };