0
0
Javaprogramming~15 mins

Method parameters in Java

Choose your learning style8 modes available
menu_bookIntroduction

Method parameters let you send information into a method so it can use that information to do its job.

When you want a method to work with different values each time it runs.
When you want to reuse a method but with different inputs.
When you want to organize your code by breaking tasks into smaller parts that need information.
When you want to calculate something based on values given when calling the method.
When you want to pass data like numbers, text, or objects into a method.
regular_expressionSyntax
Java
returnType methodName(type1 param1, type2 param2, ...) {
    // method body
}

Parameters are listed inside the parentheses separated by commas.

Each parameter has a type and a name.

emoji_objectsExamples
line_end_arrow_notchThis method takes one parameter called name of type String and prints a greeting.
Java
void greet(String name) {
    System.out.println("Hello, " + name + "!");
}
line_end_arrow_notchThis method takes two int parameters and returns their sum.
Java
int add(int a, int b) {
    return a + b;
}
line_end_arrow_notchThis method takes three parameters of different types and prints information about a person.
Java
void printInfo(String name, int age, boolean isStudent) {
    System.out.println(name + " is " + age + " years old.");
    System.out.println("Student: " + isStudent);
}
code_blocksSample Program

This program defines a method introduce that takes a name and age, then prints them. The main method calls introduce twice with different values.

Java
public class Main {
    // Method with parameters
    static void introduce(String name, int age) {
        System.out.println("My name is " + name + ".");
        System.out.println("I am " + age + " years old.");
    }

    public static void main(String[] args) {
        introduce("Alice", 30);
        introduce("Bob", 25);
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch

Parameter names should be clear to show what data they hold.

line_end_arrow_notch

Parameters are local to the method and cannot be used outside it.

line_end_arrow_notch

You can have zero or many parameters in a method.

list_alt_checkSummary

Method parameters let you send data into methods to use inside them.

Parameters have a type and a name, and are listed inside parentheses.

Using parameters makes methods flexible and reusable with different inputs.