Download Understanding Methods, Method Call Stack, and Activation Records in Java - Prof. Ruigang Y and more Study notes Computer Science in PDF only on Docsity!
In this lecture you will learn:
Static method
common Math methods available in the Java API.
To understand the mechanisms for passing
information between methods.
How the method call/return mechanism is supported
by the method call stack and activation records.
How packages group related classes.
Example: random number generatorExample: random number generator
Scoping
Method overloading
6.1 Introduction
6.2 Program Modules in Java
6.3 static Methods, static Fields and Class
Math
6.4 Declaring Methods with Multiple Parameters
6 5 6 .5 NNotes on Declaring and Using Methods D l i d U i M h d
6.6 Method Call Stack and Activation Records
6.7 Argument Promotion and Casting
6.8 Java API Packages
6.9 Case Study: Random-Number Generation
6.9.1 Generalized Scaling and Shifting of Random
Numbers
6.9.2 Random-Number Repeatability for
Testing and Debugging
6.10 Case Study: A Game of Chance
(Introducing Enumerations)
6.11 Scope of Declarations
6.12 Method Overloading
6 136.13 (Optional) GUI and Graphics Case Study:(Optional) GUI and Graphics Case Study:
Colors and Filled Shapes
6.14 (Optional) Software Engineering Case
Study: Identifying Class Operations
6.15 Wrap-Up
Methods
Called functions or procedures in some otherCalled functions or procedures in some other
languages
Modularize programs by separating its tasks into
self-contained units
Enable a divide-and-conquer approach
Are reusable in later programs
PPrevent repeating code t ti d
A method Æ a single, well-defined task
static method (or class method)
Applies to the class as a whole instead of aApplies to the class as a whole instead of a
specific object of the class
Call a static method by using the method call:
ClassName. methodName ( arguments )
All methods of the Math class are static
| example: Math.sqrt( 900.0 )
Constants
KeywordKeyword finalfinal
Cannot be changed after initialization
static fields (or class variables)
Are fields where one copy of the variable is
shared among all objects of the class
Math.PI and Math.E are final static
fields of the Math class
Same as C/C++, multiple parameters can be
declared by specifying a comma-separateddeclared by specifying a comma-separated
list.
int foo(int inputA, int inputB)
3 import java.util.Scanner; 4 55 public class MaximumFinderpublic class MaximumFinder 6 { 7 // obtain three floating-point values and locate the maximum value 8 public void determineMaximum() 9 { 10 // create Scanner for input from command window 11 Scanner input = new Scanner( System.in ); 12 13 // obtain user input 14 System.out.print( 15 "Enter three floating-point values separated by spaces: " ); 16 double number1 = input nextDouble(); // read first double
16 double number1 = input.nextDouble(); // read first double 17 double number2 = input.nextDouble(); // read second double 18 double number3 = input.nextDouble(); // read third double 19 20 // determine the maximum value 21 double result = maximum( number1, number2, number3 ); 22 23 // display maximum value 24 System.out.println( "Maximum is: " + result ); 25 } // end method determineMaximum 26
Call method maximum
Display maximum value
2727 //// returns the maximumreturns the maximum of itsof its three double parameterthree double parameterss
28 public double maximum( double x, double y, double z )
30 double maximumValue = x; // assume x is the largest to start
32 // determine whether y is greater than maximumValue
33 if ( y > maximumValue )
34 maximumValue = y;
36 // determine whether z is greater than maximumValue
37 if ( i V l )
Declare the maximum method
Compare y and maximumValue
37 if ( z > maximumValue )
38 maximumValue = z;
40 return maximumValue;
41 } // end method maximum
42 } // end class MaximumFinder
Compare z and maximumValue
Return the maximum value
1 // Fig. 6.4: MaximumFinderTest.java 22 //// Application to test classApplication to test class MaximumFinderMaximumFinder. 3 4 public class MaximumFinderTest 5 { 6 // application starting point 7 public static void main( String args[] ) 8 { 9 MaximumFinder maximumFinder = new MaximumFinder(); 10 maximumFinder.determineMaximum(); 11 } // end main 12 } // end class MaximumFinderTest
Create a MaximumFinder object
Call the determineMaximum method
12 } // end class MaximumFinderTest
Enter three floating-point values separated by spaces: 9.35 2.74 5. Maximum is: 9.
Enter three floating-point values separated by spaces: 5.8 12.45 8. Maximum is: 12.
Enter three floating-point values separated by spaces: 6.46 4.12 10. Maximum is: 10.
Confusing the + operator used for string
concatenation with the + operator used for
addition can lead to strange results.
"y + 2 = " + y + 2 (???)
Three ways to call a method:
Use a method name by itself to call anotherUse a method name by itself to call another
method of the same class
Use a variable containing a reference to an
object, followed by a dot (.) and the method
name to call a method of the referenced object
Use the class name and a dot (.) to call a
staticstatic method of a classmethod of a class
static methods cannot call non-static
methods of the same class directly
Three ways to return control to the calling
statement:statement:
No return result:
| Program flow reaches the method-ending right brace
or
| Program executes the statement return;
With a return result:
| Program executes the statementog a^ e ecutes t e state^ e t returnetu^ expressione p ess o^ ;;
y expression is first evaluated and then its value is
returned to the caller
Declaring a method outside the body of aDeclaring a method outside the body of a
class declaration or inside the body of
another method is a syntax error.
Omitting the return-value-type in a method
declaration is a syntax error.
Placing a semicolon after the rightPlacing a semicolon after the right
parenthesis enclosing the parameter list of a
method declaration is a syntax error. E.g. no
foo(int a, int b);
A method’s local variables are stored in a portion
of this stack known as the method’s activationof this stack known as the method s activation
record or stack frame
| When the last variable referencing a certain object is
popped off this stack, that object is no longer
accessible by the program
y Will eventually be deleted from memory during
“garbage collection”
|| Stack overflow occurs when the stack cannot allocateStack overflow occurs when the stack cannot allocate
enough space for a method’s activation record
Argument promotion
Automatic promotion Method argumentsAutomatic promotion Method arguments
Values in an expression are promoted to the
“highest” type in the expression
| a temporary copy of the value is made
Converting values to lower types results in a
compilation error, unless using cast
|| exampleexample(( intint )) 4 5 4.
Type Valid promotions
double None float double long float or double int long , float or double char int , long , float or double short int , long , float or double (but not char ) byte short , int , long , float or double (but not char ) boolean None ( boolean values are not considered to be numbers in Java)
Converting a primitive-type value to anotherg p yp
primitive type may change the value if the new
type is not a valid promotion. For example,
converting a floating-point value to an integral
value may introduce truncation errors (loss of
the fractional part) into the result.
Package Description
java.net (^) The Java Networking Package contains classes and interfaces that enable programs to
communicate via computer networks like the Internet. (You will learn more about this in Chapter 24, Networking.) java.text (^) The Java Text Package contains classes and interfaces that enable programs to manipulate
numbers, dates, characters and strings. The package provides internationalization capabilities that enable a program to be customized to a specific locale (e.g., a program may display strings in different languages, based on the user’s country). java.util (^) The Java Utilities Package contains utility classes and interfaces that enable such actions as date
and time manipulations, random-number processing (class Random ), the storing and processing of large amounts of data and the breaking of strings into smaller pieces called tokens (class StringTokenizer ). (You will learn more about the features of this package in Chapter 19, Collections.)) javax.swing (^) The Java Swing GUI Components Package contains classes and interfaces for Java’s Swing
GUI components that provide support for portable GUIs. (You will learn more about this package in Chapter 11, GUI Components: Part 1 and Chapter 22, GUI Components: Part 2.) javax.swing.event (^) The Java Swing Event Package contains classes and interfaces that enable event handling (e.g.,
responding to button clicks) for GUI components in package javax.swing. (You will learn more about this package in Chapter 11, GUI Components: Part 1 and Chapter 22, GUI Components: Part 2.)
The online Java API documentation is easy to
search and provides many details about each
class. As you learn a class in this book, you
should get in the habit of looking at the class
in the online documentation for additional
information.
Random-number generation
staticstatic methodmethod randomrandom from classfrom class MathMath
| Returns doubles in the range 0.0 <= x < 1.
class Random from package java.util
| Can produce pseudorandom boolean, byte, float,
double, int, long and Gaussian values
1 // Fig. 6.7: RandomIntegers.java 2 // Shifted and scaled random integers. 3 import java.util.Random; // program uses class Random
44 Import class Random from the java util package
5 public class RandomIntegers 6 { 7 public static void main( String args[] ) 8 { 9 Random randomNumbers = new Random(); // random number generator 10 int face; // stores each random integer generated 11 12 // loop 20 times 13 for ( int counter = 1; counter <= 20; counter++ ) 14 { 15 // pick random integer from 1 to 6 16 face = 1 + randomNumbers.nextInt( 6 );
Import class Random from the java.util package
Create a Random object
Generate a random die roll
18 System.out.printf( "%d ", face ); // display generated value 19 20 // if counter is divisible by 5, start a new line of output 21 if ( counter % 5 == 0 ) 22 System.out.println(); 23 } // end for 24 } // end main 25 } // end class RandomIntegers
18 int face; // stores most recently rolled value 19 20 // summarize results of 6000 rolls of a die 21 for ( int roll = 1; roll <= 6000; roll++ ) 22 { 23 face = 1 + randomNumbers.nextInt( 6 ); // number from 1 to 6 24 25 // determine roll value 1-6 and increment appropriate counter 26 switch ( face ) 27 { 28 case 1: 29 ++frequency1; // increment the 1s counter 30 break;
Iterate 6000 times
Generate a random die roll
30 break; 31 case 2: 32 ++frequency2; // increment the 2s counter 33 break; 34 case 3: 35 ++frequency3; // increment the 3s counter 36 break; 37 case 4: 38 ++frequency4; // increment the 4s counter 39 break; 40 case 5: 41 ++frequency5; // increment the 5s counter 42 break; 43 6
switch based on the die roll
43 case 6: 44 ++frequency6; // increment the 6s counter 45 break; // optional at end of switch 46 } // end switch 47 } // end for 48
49 System.out.println( "Face\tFrequency" ); // output headers 5050 SystemSystem.out.printf( "1\t%d\n2\t%d\n3\t%d\n4\t%d\n5\t%d\n6\t%d\n", out printf( "1\t%d\n2\t%d\n3\t%d\n4\t%d\n5\t%d\n6\t%d\n" 51 frequency1, frequency2, frequency3, frequency4, 52 frequency5, frequency6 ); 53 } // end main 54 } // end class RollDie
Face Frequency 1 982 2 1001 3 1015 4 1005 5 1009 6 988
Display die roll frequencies
Face Frequency 1 1029 2 994 3 1017 4 1007 5 972 6 981
To generate a random number in certain
sequence or rangesequence or range
Use the expression
shiftingValue + differenceBetweenValues *
randomNumbers.nextInt( scalingFactor )
where:
| shiftingValue is the first number in the desired range
of values
| differenceBetweenValues represents the difference
between consecutive numbers in the sequence
| scalingFactor specifies how many numbers are in the
range
To get a Random object to generate the
same sequence of random numbers everysame sequence of random numbers every
time the program executes, seed it with a
certain value
When creating the Random object:
Random randomNumbers =
new Random( seedValue );
Use theUse the setSeedsetSeed method:method:
randomNumbers.setSeed( seedValue );
seedValue should be an argument of type long