Summary Section 6.1 Introduction • Experience has shown that the best way to develop and maintain a large program is to construct it from small, simple pieces, or modules. This technique is called divide and conquer. Section 6.2 Program Modules in Java • Methods are declared within classes. Classes are typically grouped into packages so they can be imported and reused. • Methods allow you to modularize a program by separating its tasks into self-contained units. The statements in a method are written only once and hidden from other methods. • Using existing methods as building blocks to create new programs is a form of software reusability that allows you to avoid repeating code within a program. Section 6.3 static Methods, static Fields and Class Math • A method call specifies the name of the method to call and provides the arguments that the called method requires to perform its task. When the method call completes, the method returns either a result, or simply control, to its caller. • A class may contain static methods to perform common tasks that do not require an object of the class. Any data a static method might require to perform its tasks can be sent to the method as arguments in a method call. A static method is called by specifying the name of the class in which the method is declared followed by a dot (.) and the method name, as in ClassName.methodName(arguments) • Class Math provides static methods for performing common mathematical calculations. • The constant Math.PI is the ratio of a circle’s circumference to its diameter. The constant Math.E is the base value for natural logarithms (calculated with static Math method log). • Math.PI and Math.E are declared with the modifiers public, final and static. Making them public allows you to use these fields in your own classes. A field declared with keyword final is constant—its value cannot be changed after it’s initialized. Both PI and E are declared final because their values never change. Making these fields static allows them to be accessed via the class name Math and a dot (.) separator, just like class Math’s methods. • All the objects of a class share one copy of the class’s static fields. Together the class variables and instance variables represent the fields of a class. • When you execute the Java Virtual Machine (JVM) with the java command, the JVM loads the class you specify and uses that class name to invoke method main. You can specify additional command-line arguments that the JVM will pass to your application. • You can place a main method in every class you declare—only the main method in the class you use to execute the application will be called by the java command. Section 6.4 Declaring Methods with Multiple Parameters • When a method is called, the program makes a copy of the method’s argument values and assigns them to the method’s corresponding parameters. When program control returns to the point in the program where the method was called, the method’s parameters are removed from memory. • A method can return at most one value, but the returned value could be a reference to an object that contains many values. • Variables should be declared as fields of a class only if they’re required for use in more than one method of the class or if the program should save their values between calls to the class’s methods. • When a method has more than one parameter, the parameters are specified as a comma-separated list. There must be one argument in the method call for each parameter in the method declaration. Also, each argument must be consistent with the type of the corresponding parameter. If a method does not accept arguments, the parameter list is empty. • Strings can be concatenated using operator +, which places the characters of the right operand at the end of those in the left operand. • Every primitive value and object in Java can be represented as a String. When an object is concatenated with a String, the object is converted to a String, then the two Strings are concatenated. • If a boolean is concatenated with a String, the word "true" or the word "false" is used to represent the boolean value. • All objects in Java have a special method named toString that returns a String representation of the object’s contents. When an object is concatenated with a String, the JVM implicitly calls the object’s toString method to obtain the string representation of the object. • You can break large String literals into several smaller Strings and place them on multiple lines of code for readability, then reassemble the Strings using concatenation. Section 6.5 Notes on Declaring and Using Methods • There are three ways to call a method—using a method name by itself to call another method of the same class; using a variable that contains a reference to an object, followed by a dot (.) and the method name to call a method of the referenced object; and using the class name and a dot (.) to call a static method of a class. • There are three ways to return control to a statement that calls a method. If the method does not return a result, control returns when the program flow reaches the method-ending right brace or when the statement return; is executed. If the method returns a result, the statement return expression; evaluates the expression, then immediately returns the resulting value to the caller. Section 6.6 Method-Call Stack and Stack Frames • Stacks are known as last-in, first-out (LIFO) data structures—the last item pushed (inserted) onto the stack is the first item popped (removed) from the stack. • A called method must know how to return to its caller, so the return address of the calling method is pushed onto the method-call stack when the method is called. If a series of method calls occurs, the successive return addresses are pushed onto the stack in last-in, first-out order so that the last method to execute will be the first to return to its caller. • The method-call stack contains the memory for the local variables used in each invocation of a method during a program’s execution. This data is known as the method call’s stack frame or activation record. When a method call is made, the stack frame for that method call is pushed onto the method-call stack. When the method returns to its caller, its stack frame call is popped off the stack and the local variables are no longer known to the program. • If there are more method calls than can have their stack frames stored on the method-call stack, an error known as a stack overflow occurs. The application will compile correctly, but its execution causes a stack overflow. Section 6.7 Argument Promotion and Casting • Argument promotion converts an argument’s value to the type that the method expects to receive in its corresponding parameter. • Promotion rules apply to expressions containing values of two or more primitive types and to primitive-type values passed as arguments to methods. Each value is promoted to the “highest” type in the expression. In cases where information may be lost due to conversion, the Java compiler requires you to use a cast operator to explicitly force the conversion to occur. Section 6.9 Case Study: Secure Random-Number Generation • Objects of class SecureRandom (package java.security) can produce nondeterministic random values. • SecureRandom method nextInt generates a random int value. • Class SecureRandom provides another version of method nextInt that receives an int argument and returns a value from 0 up to, but not including, the argument’s value. • Random numbers in a range can be generated with int number = shiftingValue + randomNumbers.nextInt(scalingFactor); where shiftingValue specifies the first number in the desired range of consecutive integers, and scalingFactor specifies how many numbers are in the range. • Random numbers can be chosen from nonconsecutive integer ranges, as in int number = shiftingValue + differenceBetweenValues * randomNumbers.nextInt(scalingFactor); where shiftingValue specifies the first number in the range of values, differenceBetweenValues represents the difference between consecutive numbers in the sequence and scalingFactor specifies how many numbers are in the range. Section 6.10 Case Study: A Game of Chance; Introducing enum Types • An enum type is introduced by the keyword enum and a type name. As with any class, braces ({ and }) delimit the body of an enum declaration. Inside the braces is a comma-separated list of enum constants, each representing a unique value. The identifiers in an enum must be unique. Variables of an enum type can be assigned only constants of that enum type. • Constants can also be declared as private static final variables. Such constants are declared by convention with all capital letters to make them stand out in the program. Section 6.11 Scope of Declarations • Scope is the portion of the program in which an entity, such as a variable or a method, can be referred to by its name. Such an entity is said to be “in scope” for that portion of the program. • The scope of a parameter declaration is the body of the method in which the declaration appears. • The scope of a local-variable declaration is from the point at which the declaration appears to the end of that block. • The scope of a local-variable declaration that appears in the initialization section of a for statement’s header is the body of the for statement and the other expressions in the header. • The scope of a method or field of a class is the entire body of the class. This enables a class’s methods to use simple names to call the class’s other methods and to access the class’s fields. • Any block may contain variable declarations. If a local variable or parameter in a method has the same name as a field, the field is shadowed until the block terminates execution. Section 6.12 Method Overloading • Java allows overloaded methods in a class, as long as the methods have different sets of parameters (determined by the number, order and types of the parameters). • Overloaded methods are distinguished by their signatures—combinations of the methods’ names and the number, types and order of their parameters, but not their return types. |