Imagine that there is a black box that takes in an orange, makes juice out of it inside, and throws out orange juice. You can imagine another black box that takes in an orange, peels it inside and throws out a peeled orange. Now imagine a black box that takes in an orange, but doesn't throw anything out. Instead, once an orange is inserted, it presses some switches that turns on a TV inside the box, and the TV displays the orange. It could also juice the orange and display a glass of orange juice on the TV, or maybe a peeled orange (depends on what processing happens inside the box, just like the first two boxes), but you don't get anything out that you can use or store for later use. It just appears on the TV. Here, imagine the first black box as a function with float return type, the second as an integer return type, and the third one with a void return type. The first one processes and returns a float which you can add 1 to, subtract 5 from, or print, or just store in a variable as it is and never use it - but it's output is "tangible" to the programmer. Same for the int function. Finally, the void function also does some processing, and the processing includes calling another TV function that displays it, but it is not returned/thrown/collected anywhere. It is just used in some form and the output is visible but not tangible/storable to the programmer. Hope this helps. Answer from Major-Sense8864 on reddit.com
🌐
DataCamp
datacamp.com › doc › java › void
void Keyword in Java: Usage & Examples
Java keywordsIntroduction To JavaJava File HandlingJava Language BasicsJava ArraysJava Object-Oriented Programming ... The void keyword in Java is used to specify that a method does not return any value.
🌐
Reddit
reddit.com › r/javahelp › void methods?
r/javahelp on Reddit: Void methods?
October 29, 2024 -

I’ve been trying to find explanations or videos for so long explaining void methods to me and I just don’t get it still. Everyone just says “they dont return any value” i already know that. I don’t know what that means tho? You can still print stuff with them and u can assign variables values with them i don’t get how they are any different from return methods and why they are needed?

Top answer
1 of 14
18
Imagine that there is a black box that takes in an orange, makes juice out of it inside, and throws out orange juice. You can imagine another black box that takes in an orange, peels it inside and throws out a peeled orange. Now imagine a black box that takes in an orange, but doesn't throw anything out. Instead, once an orange is inserted, it presses some switches that turns on a TV inside the box, and the TV displays the orange. It could also juice the orange and display a glass of orange juice on the TV, or maybe a peeled orange (depends on what processing happens inside the box, just like the first two boxes), but you don't get anything out that you can use or store for later use. It just appears on the TV. Here, imagine the first black box as a function with float return type, the second as an integer return type, and the third one with a void return type. The first one processes and returns a float which you can add 1 to, subtract 5 from, or print, or just store in a variable as it is and never use it - but it's output is "tangible" to the programmer. Same for the int function. Finally, the void function also does some processing, and the processing includes calling another TV function that displays it, but it is not returned/thrown/collected anywhere. It is just used in some form and the output is visible but not tangible/storable to the programmer. Hope this helps.
2 of 14
4
I see many answers here, but I don't think they are addressing the misunderstanding OP is having. OP basically says: "They do return a value, I see it on my screen, what even is a method that doesn't return anything, it doesn't do anything!". This is because returning a value is different from doing something outside the method. A return value is a specific action that the method does with the outside world, but specifically it's the only way the method has to directly say to whatever called it "Here is the value you requested to have back". A void method can do a lot of other things, can manipulate objects you give it, can print to screen, can modify values in the program, but those are not return values (even if they seem to return something to the user), return values are specifically what comes out the method in the line it is called. To give a crude analogy: Let's take the line: int i = nextNumberAfter(5) Parameters (in this case 5) are what you provide the function with, the result is what the function provides you (in this case, probably a 6 that you later put into i, kinda like: int i <-- 6 <-- nextNumberAfter <-- 5 You take the 5, give it to nextNumberAfter, which does something, results in 6, and you put it into i. Let's see an example of a void method: printNextNumber(5) You still have parameters you put into the method, but here the method does something else to the number (it probably adds one and print to screen). It doesn't give you (the one who called the number) anything. You can't take the 6 and put it into i anymore, because the 6 is long gone to the screen, not in your code anymore. If you want to visualize it, it may be something like: <-X-- printNextNumber <-- 5 . | . |--> 6 --> (to screen) So you see the 6 escaping, but nothing is going back to you, it's going another way and you can't have it.
🌐
W3Schools
w3schools.com › java › ref_keyword_void.asp
Java void Keyword
assert abstract boolean break byte case catch char class continue default do double else enum exports extends final finally float for if implements import instanceof int interface long module native new package private protected public return requires short static super switch synchronized this throw throws transient try var void volatile while Java String Methods
Top answer
1 of 3
340

You are trying to use the wrong interface type. The type Function is not appropriate in this case because it receives a parameter and has a return value. Instead you should use Consumer (formerly known as Block)

The Function type is declared as

interface Function<T,R> {
  R apply(T t);
}

However, the Consumer type is compatible with that you are looking for:

interface Consumer<T> {
   void accept(T t);
}

As such, Consumer is compatible with methods that receive a T and return nothing (void). And this is what you want.

For instance, if I wanted to display all element in a list I could simply create a consumer for that with a lambda expression:

List<String> allJedi = asList("Luke","Obiwan","Quigon");
allJedi.forEach( jedi -> System.out.println(jedi) );

You can see above that in this case, the lambda expression receives a parameter and has no return value.

Now, if I wanted to use a method reference instead of a lambda expression to create a consume of this type, then I need a method that receives a String and returns void, right?.

I could use different types of method references, but in this case let's take advantage of an object method reference by using the println method in the System.out object, like this:

Consumer<String> block = System.out::println

Or I could simply do

allJedi.forEach(System.out::println);

The println method is appropriate because it receives a value and has a return type void, just like the accept method in Consumer.

So, in your code, you need to change your method signature to somewhat like:

public static void myForEach(List<Integer> list, Consumer<Integer> myBlock) {
   list.forEach(myBlock);
}

And then you should be able to create a consumer, using a static method reference, in your case by doing:

myForEach(theList, Test::displayInt);

Ultimately, you could even get rid of your myForEach method altogether and simply do:

theList.forEach(Test::displayInt);

About Functions as First Class Citizens

All been said, the truth is that Java 8 will not have functions as first-class citizens since a structural function type will not be added to the language. Java will simply offer an alternative way to create implementations of functional interfaces out of lambda expressions and method references. Ultimately lambda expressions and method references will be bound to object references, therefore all we have is objects as first-class citizens. The important thing is the functionality is there since we can pass objects as parameters, bound them to variable references and return them as values from other methods, then they pretty much serve a similar purpose.

2 of 3
32

When you need to accept a function as argument which takes no arguments and returns no result (void), in my opinion it is still best to have something like

  public interface Thunk { void apply(); }

somewhere in your code. In my functional programming courses the word 'thunk' was used to describe such functions. Why it isn't in java.util.function is beyond my comprehension.

In other cases I find that even when java.util.function does have something that matches the signature I want - it still doesn't always feel right when the naming of the interface doesn't match the use of the function in my code. I guess it's a similar point that is made elsewhere here regarding 'Runnable' - which is a term associated with the Thread class - so while it may have he signature I need, it is still likely to confuse the reader.

🌐
Baeldung
baeldung.com › home › java › core java › void type in java
Void Type in Java | Baeldung
January 8, 2024 - In this quick tutorial, we’ll ... us with the Void type. Its purpose is simply to represent the void return type as a class and contain a Class<Void> public value....
🌐
CodeHS
codehs.com › textbook › apcsa_textbook › 2.3
2.3 Calling a Void Method
2.2 Creating and Storing Objects (Instantiation) 2.3 Calling a Void Method · Overview · Method Signature · Using Methods · Calling Methods · User Input and the Scanner Class · Area of a Rectangle · Program Flow · Using the Scanner Class · Increase/Decrease by 1 ·
🌐
Trinket
books.trinket.io › thinkjava › chapter4.html
Void methods | Think Java | Trinket
You can use any name you want for methods, except main or any of the Java keywords. newLine and main are public, which means they can be invoked from other classes. They are both static, but we can’t explain what that means yet. And they are both void, which means that they don’t yield ...
Find elsewhere
🌐
Wikibooks
en.wikibooks.org › wiki › Java_Programming › Keywords › void
Java Programming/Keywords/void - Wikibooks, open books for an open world
void is a Java keyword. Used at method declaration and definition to specify that the method does not return any type, the method returns void. It is not a type and there is no void references/pointers as in C/C++. For example: See also: Java Programming/Keywords/return ·
🌐
GeeksforGeeks
geeksforgeeks.org › java › difference-between-void-and-non-void-methods-in-java
Difference Between Void and Non Void Methods in Java - GeeksforGeeks
September 22, 2023 - In this article, we will learn about void and non-void methods. The void method is a method that does not return any value. It is used to perform some action or operation but does not return any data. public void methodName(parameter1, parameter2, ...
🌐
Learn Java
learnjavaonline.org › en › Functions
Functions - Learn Java - Free Interactive Java Tutorial
void means this method doesn't return a value. Methods can return a single value in Java and it has to be defined in the method declaration.
🌐
SheCodes
shecodes.io › athena › 5279-what-is-void-in-java-and-what-is-it-used-for
[JavaScript] - What is Void in Java and What is it Used | SheCodes
The `void` keyword in Java is a reserved type used to specify that a method does not return any data type. ... Write a function that takes in a single number.
🌐
California State University, Northridge
csun.edu › ~jmotil › csun2003 › RoutinesInJava.pdf pdf
1 Routines: Void Methods in Java
In this case the number of repetitions, n, must be a non-negative integer. If n is provided as a real value, or a string, or boolean or negative the contract is broken. ... Syntax of a void method is shown below, at the left;Two examples of void methods are at the right.
Top answer
1 of 8
7

First, the multiply method does not return anything; it prints the product, but does not return any value.

public static void multiply(int x, int y)
    {
        int z = x*y;
        System.out.println(z); //may look like a return, but actually is a side-effect of the function.
    } //there is no return inside this block

Secondly, public static void main provides an entry point into your program. Without it, you cannot run your program. Refer to the Java documentation for more information on the usage of public static void main.

The String[] args here means that it captures the command line arguments and stores it as an array of strings (refer to the same link posted above, in the same section). This array is called args inside your main method (or whatever else you call it. Oracle cites argv as an alternate name)

System.out.print tells the program to print something to the console, while return is the result of the method. For example, if you added print all over your method to debug (a common practice), you are printing things while the program runs, but this does not affect what the program returns, or the result of the program.

Imagine a math problem - every step of the way you are "print"ing your work out onto the paper, but the result - the "answer" - is what you ultimately return.

2 of 8
2
  1. When a method does not return anything, you specify its return type as "void". Your multiply method is not returning anything. Its last line is a print statement, which simply prints the value of its arguments on the standard output. If the method ended with the line "return z", then you would not be able to compile the program with the "void" return type. You would need to change the method signature to public static int multiply(int x, int y).

  2. All Java programs do require the public static void main(String[] args) if they are to be executable. It is the starting point of any runnable Java program. Here's what it means:

a. public - the main method is callable from any class. main should always be public because it is the method called by the operating system.

b. static - the main method should be static, which means the operating system need not form an object of the class it belongs to. It can call it without making an object.

c. void - the main method does not return anything (although it may throw an Exception which is caught by the operating system)

d. String[] args - when you run the program, you can pass arguments from the command line. For example, if your program is called Run, you can execute the command java Run 3 4. In that case, the arguments would be passed to the program Run in the form of an array of Strings. You would have "3" in args[0] and "4" in args[1].

That said, you could have a Java program without a main, which will not be runnable.

I hope that helps.

🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › Void.html
Void (Java Platform SE 8 )
October 20, 2025 - Java™ Platform Standard Ed. 8 ... The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.
🌐
Quora
quora.com › Whats-the-purpose-of-void-methods-in-java
What's the purpose of void methods in java? - Quora
Answer (1 of 3): [code ]void[/code] is not a data type. You cannot create [code ]void[/code] fields in a class. It is at best a relic of the past, namely, C. At worst, it is a very confusing keyword that does not reflect its current function. [code ]procedure[/code] would have been a better alter...
🌐
O'Reilly
oreilly.com › library › view › think-java › 9781491929551 › ch04.html
Void Methods - Think Java [Book]
Chapter 4. Void MethodsSo far we’ve only written short programs that have a single class and a single method (main). In this chapter, we’ll show you how to organize longer programs... - Selection from Think Java [Book]