Menu
Coddy logo textTech

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 icon

Challenge

Easy

Create a void method named printNTimes. This method should take two arguments:

  1. A string message.
  2. 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);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals