Menu
Coddy logo textTech

Method Parameters

Part of the Fundamentals section of Coddy's Java journey — lesson 52 of 73.

The variables listed in a method declaration are called parameters; the values you supply when you call the method are called arguments. To add parameters to a method we write them inside the parenthesis ():

return_type method_name(data_type param1, data_type param2, ...) {
	// code
}

We can name the parameters as we want and we can write as many parameters as we need.

To call a method and pass arguments to it we write:

method_name(value1, value2, value3, ...);

Passing too many arguments to a method that is expecting less arguments will cause the program to fail

Example of usage:

public static void isEven(int number) {
	if (number % 2 == 0) {
		System.out.println(number + " is even");
	} else {
		System.out.println(number + " is odd");
	}
}
for (int i = 15; i < 34; i++) {
	isEven(i);
}
for (int i = 153; i < 219; i++) {
	isEven(i);
}

Here we have a method called isEven that accepts one argument called number and print if the number is even or odd. Then we call the method twice: one time for all the numbers between 15 and 34, Second time for all numbers between 153 and 219.

challenge icon

Challenge

Easy

Write a program that gets two inputs, numbers. The input numbers are the arguments of the method. 

Create a method that gets two arguments, calculates the product of them and prints it, name the method however you like.

Call the method with the input numbers.

Note! In your code, write the method before it's call/execution statements.

Try it yourself

import java.util.Scanner;

public class Main {
    // Method declaration
    
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        // Call the method with a and b as arguments
        
        scanner.close();
    }
}
quiz iconTest yourself

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

All lessons in Fundamentals