0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Java学習メモ③ 引数・戻り値・printlnとreturn

0
Last updated at Posted at 2026-05-26

メソッドの引数と戻り値

メソッドの命名例

openFile()(ファイルを開く)
sendEmail()(メールを送信する)
playMusic()(音楽を再生する)
  • キャメルケースで書く
  • 何をするメソッドなのかわかる名前にする
  • ローマ字は避ける

引数に型を指定する

⚠️Javaでは引数にも肩を指定する⚠️

public static void greet(String name) {
    System.out.println("ようこそ、" + name + "さん");
}
  • greet(String name) 👈ここで型を設定する
  • +は文字列同士を連結する

引数を渡して呼び出す

public class Main{
    public static void schoolInfo(String school, int grade){
        System.out.println("学校は" + school + "です");
        System.out.println("学年は" + grade + "年生です");
    }

    public static void main(String[] args){
        schoolInfo("大阪高校",3);
    }
}
結果
 学校は大阪高校です
 学年は3年生です
  • void 戻り値がない

【復習】main メソッドでは、下記の形がJavaで決まっている。

public static void main(String[] args)
  • public どこからでも使える
  • static クラスから直接使える
  • void 戻り値がない
  • String[] 文字列を複数入れる
  • args arguments(引数)の略
  • main(String[] args) 実行時の文字データを受け取る特別な形

returnメソッドの戻り値あり

public class Main {
    public static String getGreeting(String name){
        return "こんにちは、" + name + "さん";
    }
    public static void main(String[] args){
        // 戻り値を変数に代入
        String message = getGreeting("太郎");
        System.out.println(message);
    }
}
  • void が String になっている
  • returnを書くとその後の値が呼び出し元に返される
  • 呼び出し元は??
      getGreeting("太郎")を書いている main メソッド!!

returnメソッド使用例

public class Main{
    public static int multiply(int a, int b){
        return a * b;
    }
    public static void main(String[] args){
        int result = multiply(4, 6);
        System.out.println(result);
    
    //または↓
    System.out.println(multiply(2, 8));
    }
}
結果
 24
  16

printlnとreturnの違い

public class Main{
    //println 画面表示
    public static void showMultiply(int a, int b){
        System.out.println(a * b);
    }
    //return 値を返す
    public static int getMultiply(int a, int b){
        return a * b;
    }

    public static void main(String[] args){
    
        showMultiply(2, 4); //8と表示される

        int result = getMultiply(3, 5); //値だけ(表示はされない)
        System.out.println(result);  //15と表示される

        //さらに計算できる
        int total = getMultiply(2, 3) + getMultiply(4, 5);
        System.out.println(total);
    }
}
結果
  8
  15
  26
  • println 表示するだけ。他の計算に使うことはできない
  • return 戻り値を使ってされに計算することができる
  • メソッド結果を他で使いたい場合はreturnを使う

注意事項

  • 引数の型と戻り値の型、また呼び出し時に型を統一させる
  • 文字列と変数の結合時に+が抜けていないか確認する
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?