void
メニューを表示するにはスワイプしてください
Javaで何も返さない方法
戻り値の型がvoidの場合は特別なケースです。戻り値の型がvoidである場合、メソッドから何も返さないことを意味します。単に処理を実行し、値を返しません。このようなメソッドでもパラメータを持つことができます。
voidメソッドの使用例を見てみましょう:
Main.java
1234567891011121314151617package com.example; // do not modify the code below this comment public class Main { // method to print the string value passed as a parameter static void printStringValueFromParameter(String value) { System.out.println("Value from parameter: " + value); } public static void main(String[] args) { // creating a string variable to be passed as a parameter String string = "Hey, I'll be printed through a method!"; // calling the method and passing the string as a parameter printStringValueFromParameter(string); } }
戻り値を持たないメソッドを作成し、使用しました。このvoidメソッドはString型のパラメータを受け取り、それを画面に出力します。mainメソッドで呼び出すと、正常に動作します。
voidメソッドは、配列の出力のようなより複雑な処理も値を返さずに実行できます。mainメソッド内で1つのメソッドだけで配列を出力すると、コードがよりすっきりします。例となるコードを見てみましょう:
Main.java
12345678910111213141516171819202122232425package com.example; // do not modify the code below this comment public class Main { // method to print each element of an integer array to the console static void printIntArrayToTheConsole(int[] array) { // iterating over each element of the array and printing it for (int element : array) { System.out.print(element + " "); } // using an empty System.out.println to add a blank line in the console System.out.println(); } public static void main(String[] args) { // creating the first integer array int[] firstArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // creating the second integer array int[] secondArray = {0, 2, 4, 6, 8, 10, 12, 14, 16}; // calling the method to print both arrays printIntArrayToTheConsole(firstArray); printIntArrayToTheConsole(secondArray); } }
ご覧のとおり、配列を出力するためのメソッドを別に作成することで、コード行数を削減しています。配列を出力するたびに新しい for-each ループを書く代わりに、このメソッドを呼び出して配列をパラメータとして渡すだけで済みます。
このように、メソッドはコードの品質を大きく向上させます。コードがより読みやすく、編集しやすくなります。より複雑なプログラムや大規模なコードベースを書くようになった場合は、混乱を避けるためにも積極的にメソッドを活用することをおすすめします。メソッドを使いこなす練習を重ねることで、熟練したプログラマーになることができます。
その他の戻り値の型
任意のデータ型を戻り値として使用できます。前の章では、メソッドから int 型を返す例を紹介しましたが、String、long、double や任意の配列も返すことができます。さらに、自分で作成したユーザー定義型(クラス)を戻り値とすることも可能です。
フィードバックありがとうございます!
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください