Java
Methods
Methods, reusable segments of Java code, come in two varieties: object and static. A method is called, or invoked, from any portion of a program, at which point control passes from that line to the method body. A method can have values passed in as parameters from the calling segment. After the method finishes execution, it can return a value to the calling segment as well.
Variable Scope and Encapsulation
As a general rule, a variable exists only within the pair of braces or block in which it is declared.
-
Variables declared outside of any method in a class can be used anywhere in their class after they are declared and, depending on their visibility, can be accessed from outside the class using the dot operator (see Visibility modifiers).
-
Variables declared in a method are accessible only from within the method in which they are declared. An attempt to use a method variable outside its own method will result in a compile-time error.
-
Variables declared in a for or while loop are accessible only from within the block of code from which they are declared. Good programming practice dictates that the programmer try to avoid declaring variables in loops. Unless the variable is declared in the initialization of a for loop, each time the loop is executed, the variable would be re-declared and more memory allocated rather than reused.
Method Headers
Methods are introduced with method headers, which consist of the method’s optional modifiers, return type, name, and a method signature that consists of a set of parameters enclosed in parentheses. The parentheses denote a method header or method invocation and are not optional, even if the method takes no parameters. The method header is followed by an open brace, not a semicolon, and the compiler will catch any stray semicolons following method headers.
-
Modifiers returnType methodName(Parameters)
method body here }
Modifiers change the way the Java interpreter will allow a method to behave. They include visibility modifiers and keywords such as static, final, and synchronized.
-
Visibility modifiers: Java’s visibility modifiers— public, private, protected, and a default—encapsulate fields, methods, and classes by limiting their access from other classes.
-
public: Public fields and methods can be accessed wherever their class is accessible. Public classes can be accessed wherever their package is accessible.
-
private: Private fields and methods can be accessed only by their containing class.
-
protected: Protected fields and methods can be accessed only by classes in the same package as their containing class, and subclasses of their containing class.
-
default: A field or method not declared public, private, or protected is accessible only to classes in the same package as its containing class. A class not declared public will be accessible only within its package.
-
-
Static methods function independent of any object’s instantiation. As a result, they can access only static fields (which also exist independent of any object’s instantiation) and other static methods. The exception is that static methods can access all of the methods available to objects instantiated by the static method itself. (See also Static classes.)
-
Final methods cannot be overridden by a subclass. Final classes cannot be subclassed. Fields and variables declared final cannot have their values changed.
-
Synchronized methods are used when a program is running multiple threads of execution. Only one method declared synchronized can be running at a time. See http://java.sun.com/j2se/1.4.1/docs/api for more information on threading.
Return type: When a method completes its execution, it must return no more than one value to its calling method using the return statement. The return type in the method header must match the type, whether primitive or class, returned by the return statement. If a method does not return any value, its return type is void.
Method name: The method name is a programmer-specified name that should briefly describe what the method does. The method name does not have to be unique within a class (see Method overloading).
Method signature: The method signature lists a method’s formal parameters separated by commas. Each formal parameter consists of its type followed by a programmer-specified name. When a method is called, the variables listed as formal parameters are filled (never instantiated) with the values passed by the calling method (see Parameter passing). The combination of method name and method signature must be unique to the class (see Method overloading).
-
public static void main(String[] args) { ... }
-
private Iterator getIterator(List list) { ... }
-
public double distance (Point p1, Point p2) { ... }
-
public double 3dDistance,br/> (Point p1, Point p2, Point p3) { ... }
-
protected syncronized void holdThread
(int milliseconds) { ... }
Invoking Methods
Methods are invoked with the . (dot) operator, which separates the object invoking the method (or the class invoking a static method) from the method name and signature being invoked.
The dot operator can be used multiple times in a single statement to call multiple methods. The methods are evaluated from left to right, so the returned value of one method serves as the object on which the next method is called.
-
object.method(parameters);
-
class.method(parameters);
-
object.method1(parameters).method2(parameters) ... ;
The keyword this is used to refer to the object calling a particular method, and it allows an object to refer to itself. When an object invokes a method on itself, this is optional. Therefore, the following statements are equivalent:
-
this.myMethod();
-
myMethod();
Parameter Passing
The actual parameters sent to a method by the calling segment are listed, separated by commas, in the parentheses after the method name:
-
changeColor(Color.RED); /* red is a final field of the Color class */
-
double vol = myPrism.getVolume(height, width, length);
The number of parameters passed to a method must match the number of parameters called for in one of the method’s signatures. The passed parameters must be of same types and in the same order as in the method signature.
Java always passes parameters to methods by value.
-
Primitive types: When a primitive type is passed to a method, the value of the parameter is copied to the method variable. The actual value in the calling code remains unaffected by changes in the method copy.
-
Reference types: When a reference type is passed to a method, then the value of the object’s reference (not the actual object) is copied and used in the method. In this case, all changes to the object to which the value refers will remain after the method code terminates. Although the object reference is “passed by value,” parameter passing with reference types mimics C/C++ ”pass by reference,” eliminating the need for pointers.
Constructors: Constructors are methods that create new instances of classes. They are invoked with the new operator. A constructor is like an ordinary method with two exceptions: (1) it has no return type because it implicitly returns an instance of its class, and (2) it must have the same name as its class.
-
public class Count {
int number;
public Count(int startNumber) {
number = startNumber; }
}
Method overloading: Two methods in the same class can have the same name as long as their method signatures are different. When the method is called, Java checks the parameters of the called method against the method signatures of all like-named methods. Java executes the method whose signature matches that of the method invocation. The following example has two methods called “Thing” with different method signatures and modifiers. When the constructor for this class is called, “public Thing ()” will execute and that method will in turn call the other “Thing” method with the integer parameter.
-
public class Thing {
int size;
final int DEFAULT_SIZE = 20;
private Thing(int s) {
size = s;
}
public Thing() {
new Thing ( DEFAULT_SIZE );
}
}
Methods

