0
0

Java 引数 戻り値

Last updated at Posted at 2024-04-10

戻り値

メソッドの実行結果として返される値のこと

戻り値をもつメソッドの定義
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("この行は実行されない"); ←この文は実行されず、コンパイルエラーになる
 }
}

少しずつ難しくなってきたな:tired_face:
この辺をしっかり理解しないと:joy:

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0