Void Methods
Part of the Fundamentals section of Coddy's Java journey — lesson 57 of 73.
In Java, a void method is a method that does not return any value. When you declare a method as void, it indicates that the method performs a task or a set of operations, but it does not produce a result that needs to be returned to the caller. void methods are used when you want to perform actions like printing output, modifying object states, or executing a sequence of statements without returning a specific value.
Here's the basic structure of a void method:
public static void methodName(parameters) {
// Code to be executed
}Challenge
EasyCreate a void method named printNTimes. This method should take two arguments:
- A string
message. - An integer
n.
The method should print the message to the console n times. Use a for loop to repeat the printing.
In the main method, call printNTimes with the inputs message and the input n
Cheat sheet
A void method performs tasks without returning a value:
public static void methodName(parameters) {
// Code to be executed
}void methods are used for actions like printing output, modifying object states, or executing statements without returning a specific value.
Try it yourself
import java.util.Scanner;
public class Main {
public static void printNTimes(String message, int n) {
// Write you code here
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String msg = scanner.nextLine();
int n = scanner.nextInt();
printNTimes(msg, n);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison10Methods (Functions)
Declaring MethodsMethod ParametersReturn TypesMethod OverloadingRecap - Sigma FunctionRecap - Validation FunctionVoid Methods5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else