The last element of the signature we’ll discuss (skipping over the name, which can be anything as long as it doesn’t start with a number, just like naming conventions for variables) is the parameter list.
As with the static modifier, it can have information there or not. Just like “public
static int foo()” and “public int foo()” are different (and the inclusion or
not of the static modifier means something), the same is true of the parameter
list.
Methods are not required to have parameters, but even if they don’t, you still
need to have the () with nothing inside them—and that () communicates the fact that
the method doesn’t take anything in.
You can have as many parameters as you want (or none at all,
depending on what you are doing) in your methods, but beware of a few
considerations:
- The order you put them in the signature is the order they have to be passed in when the method is called.
- You must pass in every argument a method expects to receive, in the proper order, or you will get an error.
- Passing in arguments to a method not expecting any will result in an error.
- Not passing arguments to a method expecting them will result in an error.
- Passing the wrong type will result in an error.
Here’s an example of a method without any
parameters:
public class Greet {
public void
sayHello() {
System.out.println("Hello!");
}
public static void
main(String[] args) {
Greet greeter
= new Greet();
greeter.sayHello();
}
}
Here’s an example of a method with parameters that will
work:
public class Adder {
public int add(int
a, int b) {
return a + b;
}
public static void
main(String[] args) {
Adder adder =
new Adder();
int sum =
adder.add(3, 5);
System.out.println("Sum: " + sum);
}
}
This works because adder.add() expects two integers, and it gets 3 and 5.
And here is an example of something that won’t work—notice the addition of the integer
and the String, when the method expects two integers.
public class Adder {
public int add(int
a, int b) {
return a + b;
}
public static void
main(String[] args) {
Adder adder =
new Adder();
int sum = adder.add(3,
"5");
System.out.println("Sum:
" + sum);
}
}
In Java, objects and primitives may be parameters, but, unlike other languages, methods (which other languages call functions) cannot be.
No comments:
Post a Comment