方法是解決特定問題的程式碼塊,封裝在類別或物件中。System.out.println() 即為呼叫 System 類別的 out 物件之 println() 方法。
修飾符 返回值型別 方法名(參數型別 參數名, ...) {
// 方法主體
return 返回值;
}
組成要素:
public、static、private 等,定義存取權限。void。
/** 返回兩個整數較大值 */
public static int max(int num1, int num2) {
int result;
if (num1 > num2) result = num1;
else result = num2;
return result;
}
int larger = max(30, 40);System.out.println("Hello");呼叫時控制權轉移至被呼叫方法,執行 return 或結束主體後返回呼叫點。
public class TestMax {
public static void main(String[] args) {
int i = 5, j = 2;
int k = max(i, j);
System.out.println(i + " 和 " + j + " 比較,最大值是:" + k);
}
public static int max(int num1, int num2) { /* ... */ }
}
// 輸出:5 和 2 比較,最大值是:5
public static void printGrade(double score) {
if (score >= 90) System.out.println('A');
else if (score >= 80) System.out.println('B');
else if (score >= 70) System.out.println('C');
else if (score >= 60) System.out.println('D');
else System.out.println('F');
}
// 呼叫:printGrade(78.5); // 輸出 C
Java 採值傳遞:基本型別傳遞值的副本;參考型別傳遞參考的副本(指向同一物件)。
public static void swap(int n1, int n2) {
int temp = n1; n1 = n2; n2 = temp; // 僅影響區域變數
}
public static void main(String[] args) {
int num1 = 1, num2 = 2;
swap(num1, num2);
System.out.println(num1 + " " + num2); // 輸出 1 2(未改變)
}
同一類別中,方法名相同、參數列表不同(型別/個數/順序)。編譯器依據方法簽名決定呼叫哪個版本。
public static int max(int a, int b) { ... }
public static double max(double a, double b) { ... }
public static int max(int a, int b, int c) { ... }
規則: 僅靠返回型別或修飾符不同無法構成重載。

同一方法不同非巢狀區塊可重複宣告同名區域變數,但巢狀區塊內不可重複宣告。
main(String[] args) 接收執行時傳入的參數:
public class CommandLine {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}
}
// 執行:java CommandLine this is a test 200 -100
// 輸出 args[0]~args[6] 對應各參數
class MyClass {
int x;
MyClass(int i) { x = i; }
}
public class ConsDemo {
public static void main(String[] args) {
MyClass t1 = new MyClass(10);
MyClass t2 = new MyClass(20);
System.out.println(t1.x + " " + t2.x); // 10 20
}
}
JDK 1.5+ 支援:typeName... parameterName。一個方法僅能有一個可變參數,且必須是最後一個參數。
public static void printMax(double... numbers) {
if (numbers.length == 0) { System.out.println("No argument"); return; }
double max = numbers[0];
for (double n : numbers) if (n > max) max = n;
System.out.println("Max: " + max);
}
// 呼叫:printMax(34, 3, 56.5); 或 printMax(new double[]{1,2,3});
物件被垃圾回收前由 JVM 呼叫,用於釋放非記憶體資源(如關閉檔案)。
protected void finalize() throws Throwable {
super.finalize();
// 清理程式碼
}
注意: 不保證一定執行,現代 Java 建議使用 try-with-resources 或 AutoCloseable 管理資源。