Menu
Coddy logo textTech

Method Parameters

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

An argument in a method is a value that you pass into the method when you call it. To add arguments to a method we write them inside the parenthesis ():

return_type method_name(data_type arg1, data_type arg2, ...) {
	// code
}

We can name the arguments as we want and we can write as many arguments 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.

Cheat sheet

Method arguments are values passed into a method when calling it. Define arguments inside parentheses with their data types:

return_type method_name(data_type arg1, data_type arg2, ...) {
	// code
}

Call a method by passing values as arguments:

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

Example with one argument:

public static void isEven(int number) {
	if (number % 2 == 0) {
		System.out.println(number + " is even");
	} else {
		System.out.println(number + " is odd");
	}
}

// Calling the method
isEven(15);

Passing too many arguments to a method will cause the program to fail

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