...

/

Method parameters and return values

Method parameters and return values

Learn how to define methods in Java, with typed method parameters and typed return values.

We'll cover the following...

Like C, Python, and Javascript functions, a method may take parameters, and may return a single value. Of course, that single value may be a reference to a list, an object, or an array that contains other values. All value in Java must have a type, and method declarations must indicate the type of parameters and the return value.

Method parameters

Here is an example of the syntax to declare a method that takes parameters:

Press + to interact
class MethodParameters {
public static void printMyNumber(int x) {
System.out.println("My favorite number is " + x + ".");
}
public static void main(String[] args) {
printMyNumber(42);
}
}

Parameters are local variables of the method. In the definition of printMyNumber(int x), the code int x declares a new int variable, x. When the method is called, the value 42 is copied into the variable x, and then the code of printMyNumber is executed.

What happens if you call printMyNumber with a double value? The compiler will notice that you are passing in a double, and that the precision of the variable x is int. The compiler will give you ...