Skip to content

Instantly share code, notes, and snippets.

@amippy
Last active March 20, 2016 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amippy/cf2ce1aa3614b83c4844 to your computer and use it in GitHub Desktop.
Save amippy/cf2ce1aa3614b83c4844 to your computer and use it in GitHub Desktop.
筋トレ大好きな文系女学生のJava入門〜メソッド〜 ref: http://qiita.com/amippy/items/acca2cda0a2b95a66c94
メソッドの定義
public static 戻り値の型 メソッド名(引数){
 メソッドが呼び出された時に実行される処理
}
1 public class Muscle {
2 public static void main(String[] args){
3 System.out.println("これからメソッドを呼び出すよ");
4 body();  /*メソッドの呼び出し*/
5 System.out.println("メソッドの呼び出し終了!");
6 }
7 public static void body(){
8 System.out.println("プロテイン飲んでますか?");
9 }
10}
値の戻し方
public static 戻り値の型 メソッド名(引き数){
メソッドが実行された時に動く処理
 return 戻り値;
}
1 public class Muscle{
2 public static int add(int x, int y){ /*戻り値がintだからint型にする*/
3 int answer = x + y;
4 return answer;
5 }
6 public static void main(String[] args){
7 int answer = add(10,20); /*addメソッドの呼び出しで30になる*/
8 System.out.println("10+20="+answer);
9 }
10}
1 public class Muscle{
2 public static int body(int x, int y){ /*1つめのbodyメソッド*/
3 return x + y;
4 }
5 public static int body(String x, String y){ /*2つめのbodyメソッド*/
6 return x + y;
7 }
8 public static int body(double x, double y){ /*3つめのbodyメソッド*/
9 return x + y;
10 }
11 public static void main(String[] args){
12 System.out.println(add(10,20));       /*1つめのbodyメソッドが呼び出される*/
13 System.out.println(add("Muscle","World")); /*2つめのbodyメソッドが呼び出される*/
14 System.out.println(add(2.0,1.3)); /*3つめのbodyメソッドが呼び出される*/
15 }
16}
1 public calss Muscle{
2 public static int body(int x, int y){
3 return x + y;
4 }
5 public static int body(int x, int y, int z){
6 return x + y + z;
7 }
8 public static void main(String[] args){
9 System.out.println("50+30=" + body(50,30));
10 System.out.println("50+30+20=" + body(50,30,20));
11 }
12}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment