戻り値
メソッドの実行結果として返される値のこと
戻り値をもつメソッドの定義
public static 戻り値の型 メソッド名(引数リスト) {
メソッドの処理
return 戻り値;
}
戻り値を利用したメソッドの呼び出し
型 変数名 = メソッド名(引数リスト);
例)
public class Main {
public static void main(String[] args) {
// 戻り値を利用したメソッドの呼び出し
int result = add(5, 3);
System.out.println("合計: " + result);
}
// メソッドの定義
public static int add(int num1, int num2) {
// メソッドの処理
int sum = num1 + num2;
// 戻り値の返却
return sum;
}
}
戻り値をそのまま使う
☆変数に格納したコード
public class Main {
public static void main(String[] args) {
\\addメソッドを呼び出し、その結果を変数`result`に格納
int result = add(5, 3);
System.out.println("Result: " + result);
}
public static int add(int a, int b) {
return a + b;
}
}
☆戻り値をそのまま使ったコード
public class Main {
public static void main(String[] args) {
System.out.println("Result: " + add(5, 3));
}
public static int add(int a, int b) {
return a + b;
}
}
return文
return文は値を戻す役割だけではなく、メソッドの終了も行う
public class Main {
public static void main(String[] args) {
System.out.println("Result: " + a());
}
public static int a() {
return 42;
System.out.println("この行は実行されない"); ←この文は実行されず、コンパイルエラーになる
}
}
少しずつ難しくなってきたな
この辺をしっかり理解しないと