2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Java入門 戻り値の利用

Posted at

Java入門
戻り値の利用

メソッドから呼び出し元に戻されるデータを戻り値といいます。

sample.java
public class Sample {
	public static void main(String[] args) {
		int answer = add(100, 50);

		System.out.println("100 + 50 = " + answer);
	}
	// 2つの値を合計するメソッド
	public static int add (int x, int y) {
		int answer = x + y;
		// 合計を変数answerに格納してmainメソッドに返す
		return answer;
	}
}

実行結果

sample
100 + 50 = 150

addメソッドのreturnを注目してください。この設計ではreturnの横に書かれた変数answerに2つの値の合計を格納して
mainメソッドに渡しています。
returnは変数だけでなく、整数値や文字列を直接記入することも可能です。

addメソッドの型を注目して下さい。ここの型はreturnによって戻される値と同じ型を指定します。今回は整数値を戻すのでint型と指定します。ここは文字列であればString型、戻すものがなければvoidを指定します。

return文はメソッドの終了も意味します。return文の下に処理を書いても実行されず、コンパイルエラーになるので注意しましょう。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?