Monday, 22 August 2011

Java: Method Parameters

When we want to call a function, but want the result to be based on input, we use parameters. An example we've already seen of this is in System.out.println(), with the desired text being the parameter, and what gets printed out.

To have this functionality inside a method you create, you need to place the type, and give a name to, a variable inside the brackets right after the name.

public int doubleNumber(int parameter) {
return 2*parameter;

In here, you need to call the function doubleNumber with some value in it, named parameter. Inside the function you can do whatever you want with the variable. Simple. To place in multiple parameters, we just separate them by a comma.

public int multiply(int a, int b) {
return a*b;

Short update, next time: Recursion

No comments:

Post a Comment