Зміст курсу
Java Extended
Java Extended
Void
How to return nothing?
There is a special case when the return type is void
. When the return type is void
, it means that we are not returning anything from our method. It simply performs operations and does not return a value. Such a method can still have parameters.
Let's take a look at an example of using a void
method:
Main
package 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); } }
We have written and used a method that does not return anything. This void
method takes a parameter of type String
and prints it to the screen. We call it in the main
method, and it works fine.
A void
method can also perform more complex operations without returning anything, such as printing an array. It will be much cleaner when we print an array using just one method in the main method. Let's take a look at an example code:
Main
package 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); } }
As you can see, we saved lines of code by writing a separate method for printing the array. Instead of repeatedly writing a new for-each
loop to print the array, we simply call this method and pass the array as a parameter.
In this way, we can say that methods greatly improve our code. They make it more readable and easier to edit. As you are already writing more complex programs and larger codebases, I recommend using methods more often to avoid confusion. Practicing with methods will make you a truly proficient programmer.
Other return types
You can use any data type as a return value. In previous chapters, we have already returned an int
type from a method. You can also return String
, long
, double
, or any arrays. We can even return a user-defined type (class) created by us.
Дякуємо за ваш відгук!