In Java, a void
function (or method) does not return any value. However, you can use the return
statement to exit the method early if needed. The return
statement in a void
method does not return any value, it simply exits the method.
Do I Return in a Void Function in Java? Examples
Here’s an example:
public class Ex1 { public static void main(String[] args) { // Define items and their weights printMessage(true); printMessage(false); } public static void printMessage(boolean condition) { if (condition) { System.out.println("Condition is true!"); return; // Exits the method early if condition is true } System.out.println("Condition is false!"); } }
Output
Condition is true! Condition is false!