0% found this document useful (0 votes)
10 views99 pages

ch05

Chapter 5 discusses methods in programming, emphasizing their importance in organizing and maintaining large codebases through a divide and conquer approach. It covers the declaration, invocation, and reusability of methods, including static methods and method overloading. The chapter also introduces concepts such as method-call stacks, argument promotion, and secure random number generation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views99 pages

ch05

Chapter 5 discusses methods in programming, emphasizing their importance in organizing and maintaining large codebases through a divide and conquer approach. It covers the declaration, invocation, and reusability of methods, including static methods and method overloading. The chapter also introduces concepts such as method-call stacks, argument promotion, and secure random number generation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 99

Chapter 5: Methods

Badour AlBahar
Kuwait University

Slides adopted from:


ENG-200 Java How to Program, 10/e Late Objects Version
Fall 2024
Introducing Methods
• Best way to develop and maintain a large program is to construct it
from small, simple pieces.
• called divide and conquer
• Methods facilitate the design, implementation, operation and
maintenance of large programs.
• Normally, methods are called on specific objects.
• static methods can be called on a class rather than an object.
Introducing Methods
• The statements in method bodies are written only once, are hidden
from other methods and can be reused from several locations in a
program.
• Software reusability
• using existing methods as building blocks to create new programs
• Often, you can create programs from existing classes and methods
rather than by building customized code
• Dividing a program into meaningful methods makes the program
easier to debug and maintain.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
Introducing Methods
• A method is invoked by a method call
• When the called method completes its task, it returns control—and
possibly a result—to the caller
• Similar to the hierarchical form of management (Fig. 5.1)
• A boss (the caller) asks a worker (the called method) to perform a task and
report back (return) the results after completing the task
• The boss method does not know how the worker method performs its
designated tasks
• The worker may also call other worker methods, unbeknown to the boss
• This “hiding” of implementation details promotes good software engineering
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
Declaring Methods
• What is a Method?
• A method is a block of code designed to perform a specific task.
• Helps organize and reuse code.
• Allows you to divide complex programs into smaller, more manageable
pieces.

• Syntax of a Method:
accessModifier returnType methodName(parameterList) {

// method body

}
Declaring Methods
accessModifier returnType methodName(parameterList) {

// method body

Method header
• Modifiers, return type, method name and parameters
Method body
• Delimited by left and right braces
• Contains one or more statements that perform the method’s task
A return statement
• returns a value (or just control) to the point in the program from which the
method was called
Declaring Methods
accessModifier returnType methodName(parameterList) {

// method body

accessModifier: Determines method visibility (e.g., public, private).


• For now, we begin every method declaration with the keyword public
• You’ll learn about non-public methods in Chapter 7
• A public method is “available to the public”. It can be called from methods of
other classes.
Declaring Methods
accessModifier returnType methodName(parameterList) {

// method body

returnType:
• Specifies the type of data a method returns (that is, gives back to its
caller) to the calling method after performing its task
• In some cases, you’ll define methods that perform a task but will not
return any information
• Such methods use the return type void.
Declaring Methods
accessModifier returnType methodName(parameterList) {

// method body

methodName:
• Method names begin with an initial lowercase letter.
• For a method that requires additional information to perform its task, the
method can specify one or more parameters (parameterList) that represent
that additional information.
• Defined in a comma-separated parameter-list located in the parentheses that follow
the method name
• Each parameter must specify a type and an identifier
• A method’s parameters are considered to be local variables of that method and can
be used only in that method’s body
static Methods
• Sometimes a method performs a task that does not depend on the
contents of any object
• Method applies to the class in which it’s declared as a whole and is known as
a static method or a class method
• For any class imported into your program, you can call the class’s
static methods by specifying the name of the class in which the
method is declared, followed by a dot (.) and the method name
• All Math class methods are static
• Each is called by Math followed by a dot (.) and the name of the method.
• Method arguments may be constants, variables or expressions
static Methods
• static methods in the same class can call each other directly
• Any other class that uses a static method must fully qualify the
method name with the class name
• For now, we begin every method declaration with the keywords
public and static
• You’ll learn about non-public and non-static methods in Chapter 7.
Why Is Method main Declared static?
• When you execute the Java Virtual Machine (JVM) with the java
command, the JVM attempts to invoke the main method of the class
you specify
• Declaring main as static allows the JVM to invoke main without
creating an object of the class
Exercise
MaximumFinder
• Write a method named maximum that takes three double values as
input parameters and returns the largest of the three.
Declaring Methods Example
• Class MaximumFinder has two methods—main (lines 8–25) and
maximum (lines 28–41)
• The maximum method determines and returns the largest of three
double values
• Most methods do not get called automatically
• You must call method maximum explicitly to tell it to perform its task
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
Class Math
• Class Math declares two constants
• Math.PI (3.141592653589793)
• is the ratio of a circle’s circumference to its diameter
• Math.E (2.718281828459045)
• is the base value for natural logarithms (calculated with static Math method log)
• These constants are declared in class Math with the modifiers public, static and
final.
• public allows you to use these fields in your own classes
• static allows them to be accessed via the class name Math and a dot (.) separator
• final indicates that they are constants—value cannot change after they are initialized.
• A class’s variables are sometimes called fields.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
Class Math
We can implement method maximum by reusing method Math.max
• The entire body of our maximum method could also be implemented with
two calls to Math.max, as follows:

public static double maximum(double x, double y, double z) {


return Math.max(x, Math.max(y, z));
}
Declaring and Using Methods
• Three ways to call a method:
1. Using a method name by itself to call another method of the
same class
• Example: Calling maximum in the same Class

public static void main(String[] args) {


// Calling maximum directly within the same class
double max = maximum(3.5, 7.8, 1.2);
System.out.println("The maximum value is: " + max);
}
Declaring and Using Methods
• Three ways to call a method:
2. Using an object’s variable name followed by a dot (.) and the
method name to call a non-static method of the object
• Example: Calling nextInt from Scanner

public static void main(String[] args) {


// Create a Scanner object
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
// Call nextInt() on the scanner object
int number = scanner.nextInt();
System.out.println("You entered: " + number);
}
Declaring and Using Methods
• Three ways to call a method:
3. Using the class name and a dot (.) to call a static method of a
class
• Example: Calling max from Math

public static void main(String[] args) {


int a = 10;
int b = 20;
// Call Math.max() using the class name
int max = Math.max(a, b);
System.out.println("The maximum of " + a + " and " + b + " is: " + max);
}
Declaring and Using Methods
There are three ways to return control to the statement that calls
a method:
1. If the method does not return a result, control returns when the
program flow reaches the method-ending right brace or
2. when the statement return; executes
3. If the method returns a result, the statement return expression;
evaluates the expression, then returns the result to the caller
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
Method Overloading
• Methods of the same name can be declared in the same class, as long as they have
different sets of parameters
• Called method overloading
• The compiler selects the appropriate method to call by examining the number, types and
order of the arguments in the call
• Used to create several methods that perform the same or similar tasks on different types
or different numbers of arguments
• Math methods abs, min and max are overloaded with four versions each:
• One with two double parameters
• One with two float parameters
• One with two int parameters
• One with two long parameters
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
Method Overloading
• Literal integer values are treated as type int
• Literal floating-point values are treated as type double
• By default, floating-point values are displayed with six digits of
precision if the precision is not specified in the format specifier.
Method Overloading
• Compiler distinguishes overloaded methods by their signatures
• A combination of the method’s name and the number, types and order of its
parameters, but not its return type.
• Internally, the compiler uses longer method names that include the
original method name, the types of each parameter and the exact
order of the parameters to determine whether the methods in a class
are unique in that class.
• Method calls cannot be distinguished by return type
• Overloaded methods can have different return types if the methods have
different parameter lists
• Overloaded methods need not have the same number of parameters
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
Method-Call Stack and Activation Records
• Stack data structure
• Analogous to a pile of dishes
• When a dish is placed on the pile, it’s normally placed at the top (referred to
as pushing onto the stack)
• Similarly, when a dish is removed from the pile, it’s normally removed from
the top (referred to as popping off the stack)
• Last-in, first-out (LIFO) data structures—the last item pushed onto
the stack is the first item popped from the stack
Method-Call Stack and Activation Records
• When a program calls a method, the 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
• If a series of method calls occurs, the successive return addresses are pushed onto the
stack in last-in, first-out order
• The method-call stack also contains the memory for the local variables (including the
method parameters) used in each invocation of a method
• This data, stored as a portion of the method-call stack, is known as the stack frame (or activation
record) of the method call
• When a method call is made, the stack frame for that method call is pushed onto the method call
stack
• When a method returns to its caller, the stack frame for the method call is popped off
the stack and those local variables are no longer known to the program
Argument Promotion and Casting
Argument promotion—converting an argument’s value, if possible, to
the type that the method expects to receive in its corresponding
parameter
• Such conversions may lead to compilation errors if Java’s promotion rules are
not satisfied
• These rules specify which conversions are allowed—that is, which ones can
be performed without losing data
• The 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
The primitive types and the types to which each can be promoted:

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.


© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
Random-Number Generation
• SecureRandom is a class in the java.security package used for
generating random numbers in a secure way.
• SecureRandom objects produce nondeterministic random numbers
that cannot be predicted.
• Deterministic random numbers have been the source of many software
security breaches.

• SecureRandom objects can produce random boolean, byte, float,


double, int, long and Gaussian values.
Basic Usage of SecureRandom
secureRandom.nextDouble(); - generates a random
double value in the range [0.0, 1.0), meaning it can
import java.security.SecureRandom; produce values from 0.0 up to (but not including) 1.0
public class Test {
public static void main(String[] args) {
// Create a SecureRandom instance
SecureRandom secureRandom = new SecureRandom();

// Generate random integers, floating points, and booleans


int randomInt = secureRandom.nextInt();
double randomDouble = secureRandom.nextDouble();
Boolean randomBoolean = secureRandom.nextBoolean();

// Print the results


System.out.println("Random Integer: " + randomInt);
System.out.println("Random Double: " + randomDouble);
System.out.println("Random Boolean: " + randomBoolean);
}
} Example output:
Random Integer: 320137820
Random Double: 0.10911655053883729
Random Boolean: true
Bounded Random Numbers
• Scaling Factor
• nextInt(int scalingFactor)
• The scaling factor defines the range of possible values, generating random numbers from 0 up
to (but not including) the provided argument.
• Example:
• nextInt(10) will produce numbers from 0 to 9.
• Shifting the Range:
• To adjust the range (e.g., to produce numbers from 1 to 10 instead of 0 to 9), you can
add a shifting value to the result.
• nextInt(int scalingFactor) + shiftingValue
• Adding a shifting value will start the range at shiftingValue, so numbers will go from
shiftingValue up to scalingFactor + shiftingValue - 1.
• Example:
• nextInt(10) + 1 will produce numbers from 1 to 10.
Generalizing Random Number Generation
Generating Random Numbers in a Consecutive Range
• Formula:
number = shiftingValue + randomNumbers.nextInt(scalingFactor);
• Parameters:
• shiftingValue: Specifies the starting number in the desired range.
• scalingFactor: Specifies how many numbers are in the range.
• Example:
• To generate a random number from 5 to 14:
int number = 5 + randomNumbers.nextInt(10);
• Here, shiftingValue is 5 and scalingFactor is 10.
Generalizing Random Number Generation
Generating Random Numbers in a Custom Sequence (Non-Consecutive Range)
• Formula:
number = shiftingValue + differenceBetweenValues * randomNumbers.nextInt(scalingFactor);
• Parameters:
• shiftingValue: Specifies the starting number in the desired range.
• differenceBetweenValues: The gap or difference between consecutive numbers in the
sequence.
• scalingFactor: Specifies how many numbers are in the range.
• Example:
• Generate random multiples of 5 between 10 and 30:
int number = 10 + 5 * randomNumbers.nextInt(5);
• Here, shiftingValue is 5, differenceBetweenValues is 5, and scalingFactor is 5.
• Produces values from 10, 15, 20, 25, or 30
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
Case Study
Dice Game "Craps"
1. Roll two dice and add up the values shown on the top faces.
2. On your first roll:
1. If the sum is 7 or 11, you win.
2. If the sum is 2, 3, or 12 ("craps"), you lose.
3. If the sum is 4, 5, 6, 8, 9, or 10, that value becomes your point.
3. If you have a point:
1. Keep rolling until you either roll your point again (and win) or
2. roll a 7 (and lose).
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
Class-Level Variables (Fields)
• Definition: Variables declared inside a class but outside any method
are known as class-level variables or fields.
• Purpose: Fields are used to store data that should be accessible to all
methods in the class. This data often represents properties or states
of an object created from the class.
• Scope: Fields are accessible from all methods in the class and retain
their values as long as the object exists (for instance variables) or the
program is running (for static variables).
Introduction to Enumerations
• Definition: An Enumeration, or enum, is a special Java type used to
define collections of constants.
• Purpose: enums provide a way to group related constants, making
the code more readable, type-safe, and organized.

public enum Day {


MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public enum Color {


RED, GREEN, BLUE
}
Introduction to Enumerations
• Declaring an Enum:
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public enum Color {


RED, GREEN, BLUE
}

• Usage Example:
Day today = Day.MONDAY;

Color myColor = Color.RED;


public class Main {
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public static void printWeekendStatus(Day day) {
if (day == Day.SATURDAY || day == Day.SUNDAY) {
System.out.println(day + " is a weekend.");
} else {
System.out.println(day + " is a weekday.");
}
}
public static void main(String[] args) {
Day today = Day.TUESDAY;
printWeekendStatus(today);
}
}

Output: TUESDAY is a weekday.


Enumerations
• Type Status is a private member of class Craps, because Status will be used only in that
class
• Status is an enum type
• Declares a set of constants represented by identifiers
• Special kind of class that is introduced by the keyword enum and a type name
• Braces delimit an enum declaration’s body
• 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 the constants declared in the enum
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
Enumerations
• Why we declare some constants as public final static int rather than
as enum constants:
• Java does not allow an int to be compared to an enum constant

• Unfortunately, Java does not provide an easy way to convert an int


value to a particular enum constant
Scope of Declarations
• Declarations introduce names that can be used to refer to classes,
methods, variables and parameters
• The scope of a declaration is the portion of the program that can refer
to the declared entity by its name
• Such an entity is said to be “in scope” for that portion of the program
Scope of Declarations
• Class-Level Scope
• Variables declared inside a class but outside any method
• They are accessible from all methods in the class.
• They retain their values as long as the object exists (for instance variables) or the
program is running (for static variables).
• Method-Level Scope (Local Variables)
• Variables declared within a method
• They are accessible only within the method where they are declared.
• They are created from the point at which the declaration appears and destroyed
when the method exits.
Scope of Declarations
• Block-Level Scope:
• Variables declared within a block of code (enclosed in {}), such as loops or conditional
statements, have block-level scope.
• Example: local-variable declaration that appears in the initialization section of a for statement’s header
• They are accessible only within that specific block.
• They exist only during the execution of that block.
• Parameter Scope:
• Parameters are variables declared in the method signature and are used to pass data into
methods.
• They are accessible only within the method where they are declared.
• They exist for the duration of the method call.
Scope of Declarations
• Any block may contain variable declarations
• If a local variable or parameter in a method has the same name as a field of
the class, the field is hidden until the block terminates execution
• Called shadowing
• Shadowing occurs when a local variable in a method has the same name as a class-
level variable. In this case, the local variable "shadows" the class-level variable
within the method.

• Figure 5.9 demonstrates scoping issues with static and local variables.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
String concatenation
• String concatenation allows you to assemble String objects into larger
strings by using operators + or +=
• When both operands of operator + are String objects, operator +
creates a new String object in which the characters of the right
operand are placed at the end of those in the left operand
• Example:
• "Hello" + " World" creates "Hello World".
String concatenation
• Every primitive value and object in Java can be represented as a String
• When one of the + operator’s operands is a String, the other is
converted to a String, then the two are concatenated
• Example:
• "Age: " + 25 creates "Age: 25"
• "Result: " + 4.5 creates "Result: 4.5"
String concatenation
• If a boolean is concatenated with a String, the boolean is converted to
the String "true" or "false"
• Example:
boolean status = true;
"Status: " + status creates "Status: true"
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
int y = 5;
System.out.println("y+2= " + y+2); y+2= 52
int y = 5;
System.out.println("y+2= " + (y+2)); y+2= 7

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.


Exercise
Given this method:
public static void printInfo(String message) {
System.out.println(message);
}

• What will be the output of:

printInfo(10 + 20);
printInfo("Sum: "+10+20);
printInfo("Sum: "+(10+20));
Exercise
Given this method:
public static void printInfo(String message) {
System.out.println(message);
}

• What will be the output of:

printInfo("Hello");
printInfo(10);
printInfo(102.75);
printInfo('A');
Exercise
Given this method:
public static void printInfo(String message) {
System.out.println(message);
}

• What will be the output of:

printInfo("Hello"); Specify one single method


printInfo(10); you would add to make
printInfo(102.75);
the code run without
errors?
printInfo('A');
Exercise
Given these two methods:
public static void printInfo(String message) {
System.out.println("Message: " + message);
}
public static void printInfo(double number) {
System.out.println("Number: " + number);
}

• What will be the output of:


printInfo("Hello");
printInfo(10);
printInfo(102.75);
printInfo('A');
Exercise
Given this method:
public static void printInfo(String message) {
System.out.println(message);
}

• Which method is a valid overloaded method?

1. public static int printInfo(String message)


2. public static void printInfo(int message)
3. public static void printInfo(String message1, String message2)
4. public static void printInfo(String message1, int message2)
Exercise
Given this method:
public static void printInfo(String message1, int message2) {
System.out.println(message1 + message2);
}

• Which method is a valid overloaded method?

1. public static void printInfo(int message1, String message2)


2. public static void printInfo(int message)
3. public static void printInfo(String message1, String message2)
4. public static void printInfo(String msg1, int msg2)
Exercise
Given these two Strings:
String firstName = "Zain";
String lastName = "Saleh";
String fullName = ;

• How would you combine the two Strings firstName and lastName to
get one String: ?
fullName = "Zain Saleh"
Exercise
Guess the Number Game
Write a Java program that lets the user guess a randomly generated
number.
In your program include a method, checkGuess, that evaluates the
user's guess:
• If the user’s guess is too high, print "Too high! Try again.”
• If the user’s guess is too low, print "Too low! Try again.”
• If the user guesses correctly, print "Congratulations! You guessed the
number!”
This method should return true if the guess is correct, or false if the
guess is incorrect.
Exercise
Guess the Number Game
• Try adding:
• Attempt Counter:
• Keep track of the number of guesses the user has made.
• Repeat the game option:
• After the correct guess, ask if they want to play again (Yes/No).
Exercise
Calculating Factorial Using Recursion
• The factorial of a number 𝑛 (written as 𝑛!) is the product of all
positive integers less than or equal to 𝑛.
𝑛! = 𝑛 × 𝑛 − 1 × 𝑛 − 2 × 𝑛 − 3 … 2 × 1
• For example:
5! = 5 × 4 × 3 × 2 × 1 = 120
Method factorial
// Recursive method to calculate factorial
public static int factorial(int n) {
// Base case: if n is 1, return 1 (since 1! = 1)
if (n == 1) {
return 1;
} else {
// Recursive case: n * factorial of (n - 1)
return n * factorial(n - 1);
}
}
How it Works
When factorial(5) is called:
• It returns 𝟓 × factorial(4)
• Which returns 4 × factorial(3)
• Which returns 𝟑 × factorial(2)
• Which returns 2 × factorial(1)
• Finally, factorial(1) returns 1 (base case).
Recursion
• Recursion is a powerful tool in programming but requires careful
design to avoid infinite loops. Each recursive function should have a
clear base case and move toward it in each recursive call.
Exercise
What will be the output?
public class Main {
public static void main(String[] args) {
countdown(5);
}

public static void countdown(int n) {


if (n <= 0) {
System.out.println("Liftoff!");
} else {
System.out.println(n);
countdown(n - 1);
}
}
}
Exercise
What will be the output?
public class Main {
public static void main(String[] args) {
countdown(5);
}

public static void countdown(int n) {


if (n <= 0) {
System.out.println("Liftoff!");
} else {
System.out.println(n);
countdown(n - 1);
}
}
}
Exercise
What will be the output?
public class Main {
public static void main(String[] args) {
countUp(1, 5);
}

public static void countUp(int start, int end) {


if (start > end) {
System.out.println("Done!");
} else {
System.out.println(start);
countUp(start + 1, end);
}
}
}
Exercise
Sum of All Numbers Up to n
Write a program that prompts the user to enter a positive integer n,
then calculates the sum of all integers from 1 up to n.
1. Using a Loop:
• Implement the solution using a loop (e.g., for-loop or while-loop).
2. Using Recursion:
• Implement the solution using recursion.

You might also like