
Parameters are variables that represent the arguments passed into a method. They are declared in the method declaration. Take the main method as an example:
1 2 3 4 |
public static main(String[] args) { ... } |
args is declared in the method declaration for main (inside the parentheses). Like any declaration, you need to declare its type, an array of instances of the String class. In other words, you declare the class or method, then inside the parentheses you declare what Java is supposed to be looking for. In this case it’s a set of Strings.
Parameters You’ve already seen examples of parameters, both in the
Bicycle
class and in themain
method of the “Hello World!” application. Recall that the signature for themain
method ispublic static void main(String[] args)
. Here, theargs
variable is the parameter to this method. The important thing to remember is that parameters are always classified as “variables” not “fields”. This applies to other parameter-accepting constructs as well (such as constructors and exception handlers) that you’ll learn about later in the tutorial. Java Variables
Makes perfect sense… wait… what? Variables and fields aren’t the same thing? Sigh… okay before we get into parameters let’s clear up that line.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class Bicycle(){ double speed; int gear; //Setters and Getters ommitted for space. public int changeGear(int gearShift){ int newGear; newGear = gear + gearShift; // pretend there's some conditionals here that check that the gear is valid return newGear; } } |
Let’s look at the code from example 3 (I put it above, up yonder). In Java, Non-Static Fields/ Instace Variables are ones like speed and gear. Meanwhile, newGear is a local variable. The gearShift is our parameter in question.
A field is a variable that is declared inside the class block but outside of the methods or constructors.
Parameters are the names of the variables that are going to be used inside of the method. You pass in arguments, and parameters are used inside of the method. An argument is also called an actual parameter, because it is the actual value that is being computed while the parameter is the variable itself. Meanwhile, the words arguments and parameters are mostly used interchangeably, because it is often confusing when trying to talk about your methods and it’s usually not too important to distinguish.