Methods
Methods appear inside class bodies. They contain local variable
declarations and other Java statements that are executed when the method
is invoked. Methods may return a value to the caller. They always specify
a return type, which can be a primitive type, a reference type, or the
type void , which indicates no
returned value. Methods may take arguments, which are values supplied by
the caller of the method.
Here’s a simple example:
classBird{intxPos,yPos;doublefly(intx,inty){doubledistance=Math.sqrt(x*x+y*y);flap(distance);xPos=x;yPos=y;returndistance;}...}
In this example, the class Bird
defines a method, fly(), that takes as
arguments two integers: x and y. It returns a double type value as a result, using the
return keyword.
Our method has a fixed number of arguments (two); however, methods can have variable-length argument lists, which allow the method to specify that it can take any number of arguments and sort them itself at runtime. We provide more details later in this chapter.
Local Variables
Our fly() method
declares a local variable called distance, which it uses to compute the distance flown. A local variable is temporary; it exists only within the scope (the block) of its method. Local variables are allocated when a method is invoked; they are normally destroyed when the method returns. They can’t be referenced from outside the method itself. If the method is executing concurrently in different threads, each thread has its own ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access