Methods, arguments,
and return values
In many languages (like C and C++), the term function is used to describe a named subroutine. The term that is more commonly used in Java is method, as in “a way to do something.” If you want, you can continue thinking in terms of functions. It’s really only a syntactic difference, but this book follows the common Java usage of the term “method.”
Methods in Java determine the messages an object can receive. In this section you will learn how simple it is to define a method.
The fundamental parts of a method are the name, the arguments, the return type, and the body. Here is the basic form:
returnType methodName( /* Argument list */ ) {
/* Method body */
}
The return type is the type of the value that pops out of the method after you call it. The argument list gives the types and names for the information you want to pass into the method. The method name and argument list together uniquely identify the method.
Methods in Java can be created only as part of a class. A method can be called only for an object,[11] and that object must be able to perform that method call. If you try to call the wrong method for an object, you’ll get an error message at compile time. You call a method for an object by naming the object followed by a period (dot), followed by the name of the method and its argument list, like this:
objectName.methodName(arg1, arg2, arg3);
For example, suppose you have a method f( ) that takes no arguments and returns a value of type int. Then, if you have an object called a for which f( ) can be called, you can say this:
int x = a.f();
The type of the return value must be compatible with the type of x.
This act of calling a method is commonly referred to as sending a message to an object. In the preceding example, the message is f( ) and the object is a. Object-oriented programming is often summarized as simply “sending messages to objects.”