1
2
3
4
5
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}

Java每一行程式碼都屬於一個class,class都是大寫開頭,例如Main。

main()

每個Java程式都必須要有main(),且一定會被執行。

Java Variables

type variable = value;

例如:
String name = "John"

先宣告變項,再assign數值:

1
2
int myNum;
myNum = 15;

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 -> double

  • Narrowing 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
2
3
4
5
6
7
8
9
10
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

while & do/while

差別:do/while至少會運行一次,才檢查condition

while:

1
2
3
while (condition) {
// code block to be executed
}

do/while:

1
2
3
4
do {
// code block to be executed
}
while (condition);

for-each loop

用來loop陣列(array)

1
2
3
for (type variableName : arrayName) {
// code block to be executed
}

範例:

1
2
3
4
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}

break & continue

  • break: 跳出、終止loop
  • continue: 跳出當前的loop,但會繼續到下一個

array

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

多維度:
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };