2.6. Worked Example: Call a method of Random¶
Subgoals for Calling a Method
Classify method as static method or instance method
If static, use the class name
If instance, must have or create an instance
Write (instance / class) dot method name and ( )
Determine whether parameter(s) are appropriate
Number of parameters passed must match method declaration
Data types of parameters passed must match method declaration (or be assignable)
Determine what the method will return (if anything: data type, void, print, change state of object) and where it will be stored (nowhere, somewhere)
Evaluate right hand side (RHS) of assignment (if there is one). Value is dependent on method’s purpose
You can watch this video or read through the content below it.
Problem Statement
Given the following code, how do you create a Random integer value?
Random rand = new Random();
SG1: Classify method as static method or instance method
We already have an instance of Random with the variable name rand
.
SG2: Write (instance / class) dot method name and ( )
First, check the API to find a method that does what we want.

rand.nextInt()
SG3: Determine whether parameter(s) are appropriate
According to the API documentation, the nextInt
method requires 1 parameter, the exclusive upper bound. If we want to generate random values between 0 to 99 (inclusive) then parameter will be 100.
rand.nextInt(100)
SG4: Determine what the method will return (if anything: data type, void, print, change state of object) and where it will be stored (nowhere, somewhere)
According to the API documentation, the nextInt
method returns an integer, so we need an int
type variable to store the value.
int value = input.nextInt();
SG5: Evaluate right hand side (RHS) of assignment (if there is one). Value is dependent on method’s purpose
We used the API documentation to choose the correct parameter, such that the RHS will return an integer between 0 to 99 (inclusive).
int value = input.nextInt();
Practice Pages