0% found this document useful (0 votes)
3 views24 pages

Java Methods Chapter7 InDepth

Chapter 7 of the Java Programming guide focuses on methods, detailing their significance in structuring code for better readability and maintenance. It covers predefined methods, value-returning methods, void methods, and the flow of execution, emphasizing the importance of parameters and the pass-by-value mechanism. The chapter provides practical examples and syntax guidelines to aid in understanding method implementation in Java.

Uploaded by

cabaronin
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)
3 views24 pages

Java Methods Chapter7 InDepth

Chapter 7 of the Java Programming guide focuses on methods, detailing their significance in structuring code for better readability and maintenance. It covers predefined methods, value-returning methods, void methods, and the flow of execution, emphasizing the importance of parameters and the pass-by-value mechanism. The chapter provides practical examples and syntax guidelines to aid in understanding method implementation in Java.

Uploaded by

cabaronin
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

Java Programming

From Problem Analysis to Program Design, 5e

Chapter 7 — Methods
In-Depth Technical Study Guide

Comprehensive coverage of all slides with detailed explanations,


annotated code examples, scope diagrams, and exam-ready summaries.

Topics covered in this guide:


Predefined Methods | Value-Returning Methods | Void Methods | Parameters & Pass-by-Value | Reference Variables
| Scope Rules | Method Overloading | Drivers & Stubs
Java Programming • Chapter 7: Methods In-Depth Study Guide

1. Why Methods? — Divide Your Code


In any non-trivial Java program, packing all logic into a single main() method quickly becomes unmanageable.
Methods are the primary mechanism Java provides for decomposing a large problem into smaller,
independently solvable sub-problems. This approach is formally called top-down design (or
divide-and-conquer) and is foundational to software engineering.

1.1 Formal Motivations (from the slides)


• Focused development: Each method can be designed, coded, tested, and debugged in isolation without
worrying about the rest of the program.
• Parallel development: In a team environment, different developers can work on different methods
simultaneously, dramatically reducing delivery time.
• Code reuse: A method written once can be called from multiple places in the same program, or even
imported into future projects via class libraries — eliminating redundant code (the DRY principle: Don't
Repeat Yourself).
• Improved readability: main() becomes a high-level orchestration script — short and descriptive — while
complexity is encapsulated in named methods whose signatures communicate intent.

1.2 Structural Overview


Every method in Java lives inside a class. The minimal structural pattern is:

public class HugeProgram {

public static void main(String[] args) {

doSomething1(); // delegates to separate methods

doSomething2();

doSomething3();

public static void doSomething1() { /* focused logic here */ }

public static void doSomething2() { /* focused logic here */ }

public static void doSomething3() { /* focused logic here */ }

✔ Design principle

A well-designed main() reads like a table of contents: it names what happens in order without
exposing how. All 'how' belongs inside individual methods.

From Problem Analysis to Program Design, 5e Page 2


Java Programming • Chapter 7: Methods In-Depth Study Guide

2. Predefined (Standard Library) Methods


Java ships with a rich standard library organised into packages containing classes that group related methods.
Before writing your own, always check whether a suitable predefined method already exists. The two classes
most heavily used at this stage are [Link] and [Link]. Because both belong to
[Link], they are automatically imported — no explicit import statement is required.

2.1 class Math (package: [Link])


All Math methods are public static, meaning they are called on the class itself ([Link](x)), not on an
instance. The class also exposes two named constants: [Link] (≈ 3.14159…) and Math.E (≈ 2.71828…).

Method call Example / Result Description

[Link](x) abs(-67) → 67 Absolute value. Works for int, long, float, double.

[Link](x) sqrt(4.0) → 2.0 Square root; x must be ≥ 0 (returns NaN


otherwise).

[Link](x,y) pow(2.0,3.0) → 8.0 x raised to the power y. Both params must be


double.

[Link](x) round(24.56) → 25 Rounds to nearest long (if double) or int (if float).

[Link](x) ceil(56.34) → 57.0 Smallest integer value ≥ x. Returns double.

[Link](x) floor(65.78) → 65.0 Largest integer value ≤ x. Returns double.

[Link](x,y) max(15,25) → 25 Returns the larger of x and y.

[Link](x,y) min(15,25) → 15 Returns the smaller of x and y.

[Link](x) log(2) → 0.693… Natural logarithm (base e). x must be > 0.

Math.log10(x) log10(2) → 0.301… Common logarithm (base 10).

[Link]/cos/tan sin(PI/2) → 1.0 Trig functions. Argument must be in radians.

[Link]() random() → 0.0–<1.0 Returns a random double in [0.0, 1.0).

2.2 Static Import — Dropping the Class Prefix


Java 5.0 introduced static import statements, allowing you to call public static members without qualifying
them with the class name. There are two forms:

import static [Link].*; // import ALL static members

import static [Link]; // import ONE specific member

Practical example:

From Problem Analysis to Program Design, 5e Page 3


Java Programming • Chapter 7: Methods In-Depth Study Guide

import static [Link].*;

import static [Link].*;

public class PredefinedMethods {

public static void main(String[] args) {

// Without static import you'd need: [Link](2.5, 3.5)

double result = pow(2.5, 3.5); // 24.705…

[Link](toUpperCase('a')); // A

[Link](abs(-15)); // 15

✔ Caution with static import

Importing all members with * can create name conflicts if two classes expose methods with the
same name. Prefer specific imports (e.g., import static [Link];) in production code for
clarity.

2.3 class Character (package: [Link])


The Character wrapper class provides static utility methods for inspecting and transforming char values:

Method Behaviour

[Link](ch) Returns true if ch is a lower-case letter; false otherwise.

[Link](ch) Returns true if ch is an upper-case letter; false otherwise.

[Link](ch) Returns true if ch is a decimal digit ('0'–'9').

[Link](ch) Returns true if ch is a Unicode letter.

[Link](ch) True if ch is a letter or a digit.

[Link](ch) Returns the lower-case equivalent of ch (unchanged if none).

[Link](ch) Returns the upper-case equivalent of ch (unchanged if none).

From Problem Analysis to Program Design, 5e Page 4


Java Programming • Chapter 7: Methods In-Depth Study Guide

3. Value-Returning (Non-void) Methods


A value-returning method computes a result and hands it back to the caller using a return statement. The
caller can store the result in a variable, use it directly in an expression, or pass it as an argument to another
method call.

3.1 Complete Syntax

modifier(s) returnType methodName(dataType param1, dataType param2, ...)

// method body

return expression; // expression type must match returnType

Syntax element Explanation

modifier(s) Access and behaviour keywords. Most user methods use public static at this
stage. public = accessible everywhere; static = belongs to the class, not an
instance.

returnType The data type of the value being returned. Can be any primitive (int, double,
boolean, char…) or reference type (String, array…). Must NEVER be void.

methodName A Java identifier following naming conventions (camelCase). Should be a verb


or verb-phrase that describes what the method does (e.g., calculateArea).

parameter list Comma-separated list of typed variables the method receives. Each entry is:
dataType variableName. May be empty ().

return expression The value sent back. Its type must be assignment-compatible with returnType.
Execution of the method ends immediately at return.

3.2 Anatomy of a Method: the larger() Example

// modifier returnType name formal parameters

// | | | | |

public static double larger(double x, double y)

double max; // local variable — exists only inside this method

if (x >= y) // compare the two incoming values

From Problem Analysis to Program Design, 5e Page 5


Java Programming • Chapter 7: Methods In-Depth Study Guide

max = x;

else

max = y;

return max; // send the result back to the caller

Calling this method from main() (actual parameters are the real values passed in):

double num;

num = larger(23.50, 37.80); // actual params: 23.50 and 37.80 → num = 37.80

num = larger(num1, num2); // actual params can be variables

num = larger(34.50, num1); // or a mix of literals and variables

[Link](larger(5.0, 9.0)); // result used directly in println

3.3 Equivalent Compact Forms


The following three versions are logically identical:

// Form 1: explicit local variable

public static double larger(double x, double y) {

double max;

if (x >= y) max = x; else max = y;

return max;

// Form 2: two return statements

public static double larger(double x, double y) {

if (x >= y) return x;

else return y;

// Form 3: fall-through return (no else needed)

public static double larger(double x, double y) {

if (x >= y) return x;

return y; // reached only when x < y

From Problem Analysis to Program Design, 5e Page 6


Java Programming • Chapter 7: Methods In-Depth Study Guide

✔ Compiler guarantee

The Java compiler performs definite assignment analysis. Every code path through a
value-returning method MUST reach a return statement, otherwise the compiler raises a 'missing
return statement' error.

3.4 Case Study: Dice Rolling (Example 7-3)


The rollDice(int num) method below returns the number of rolls needed before a pair of dice sums to the
target value num. It demonstrates: a do-while loop, [Link]() for simulation, and a single return at the end.

public static int rollDice(int num) {

int die1, die2, sum;

int rollCount = 0;

do {

die1 = (int)([Link]() * 6) + 1; // 1 – 6

die2 = (int)([Link]() * 6) + 1; // 1 – 6

sum = die1 + die2;

rollCount++;

} while (sum != num);

return rollCount;

(int)([Link]() * 6) + 1 works because: [Link]() returns [0.0, 1.0) → multiplying by 6


gives [0.0, 6.0) → casting to int truncates to {0,1,2,3,4,5} → adding 1 shifts to {1,2,3,4,5,6}.

From Problem Analysis to Program Design, 5e Page 7


Java Programming • Chapter 7: Methods In-Depth Study Guide

4. Void Methods
A void method performs an action (printing, modifying objects, updating variables) but does not return a
value. The keyword void replaces the return type. A method call to a void method is always a standalone
statement; it cannot appear inside an expression.

4.1 Syntax

modifier(s) void methodName(dataType param1, dataType param2, ...)

// statements

// optional early exit:

return; // terminates the method immediately; NO value after 'return'

4.2 Syntax of the Method Call

// Correct — standalone statement:

methodName(arg1, arg2);

// WRONG — void result cannot be used in an expression:

// int x = methodName(arg1); // compile error

4.3 Example — void with Parameters

public static void printResult(double value, String label) {

[Link]("%s = %.2f%n", label, value);

// Calling the method:

printResult(3.14159, "PI approximation");

// Output: PI approximation = 3.14

The actual parameter list must match the formal parameter list in number, order, and compatible types.

From Problem Analysis to Program Design, 5e Page 8


Java Programming • Chapter 7: Methods In-Depth Study Guide

4.4 Value-Returning vs Void — Decision Guide


Criterion Use value-returning / Use void

Do you need the result elsewhere? Yes → value-returning. No → void.

Is the purpose calculation? Yes → value-returning. No (printing, updating) → void.

Called inside an expression? Yes → must be value-returning.

Side-effect only (I/O, mutation)? Void is usually cleaner.

From Problem Analysis to Program Design, 5e Page 9


Java Programming • Chapter 7: Methods In-Depth Study Guide

5. Flow of Execution
Understanding the exact control flow is essential for debugging and reasoning about program correctness. The
rules are:

• Execution always begins at the first statement inside main().


• A method definition is not executed when the JVM scans over it — it is only executed when explicitly
called.
• When a method call is reached, the JVM suspends the current method and transfers control (and
arguments) to the called method.
• The called method runs to completion (or until a return) and then control resumes in the caller
immediately after the call site.
• In a call to a value-returning method, the returned value is substituted at the call site before further
evaluation of the expression.

public static void main(String[] args) { // step 1: enter main

[Link]("A"); // step 2: print A

printMessage(); // step 3: jump to printMessage

[Link]("C"); // step 5: resume, print C

int x = add(3, 4); // step 6: jump to add

[Link]("sum = " + x); // step 8: print sum = 7

} // step 9: program ends

public static void printMessage() { // step 3 → enter

[Link]("B"); // step 4: print B

} // return to step 5

public static int add(int a, int b) { // step 6 → enter

return a + b; // step 7: return 7 to step 8

✔ Output order

A → B → C → sum = 7

From Problem Analysis to Program Design, 5e Page 10


Java Programming • Chapter 7: Methods In-Depth Study Guide

6. Parameters — Formal, Actual, and Passing


Mechanisms
Parameters are the primary channel for passing information into a method. Java has two categories: formal
parameters (in the definition) and actual parameters / arguments (in the call). When a method is called, the
actual parameters are evaluated left-to-right and their values (or references) are copied into the corresponding
formal parameters.

6.1 Formal vs Actual Parameter Syntax

// ■■■■■■■ definition ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

// formal parameters (declare type + name)

public static double larger(double x, double y) { ... }

// ■■■■■■■ call sites ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

// actual parameters (concrete values / expressions)

larger(23.50, 37.80); // literals

larger(num1, num2); // variables

larger(a + b, c * 2.0); // expressions

Matching rules: the number of actual params must equal the number of formal params; each actual param's
type must be assignment-compatible with (or auto-widened to) the corresponding formal param's type.

6.2 Pass-by-Value for Primitive Types


Java is strictly pass-by-value. For primitive types (int, double, boolean, char, etc.), the value of the
actual parameter is copied into the formal parameter. The formal parameter is a completely independent local
variable inside the method. Any assignment to it has no effect on the original variable.

public static void main(String[] args) {

int num = 6;

tryToChange(num);

[Link](num); // still 6 — unaffected

public static void tryToChange(int x) {

x = x + 10; // only modifies the LOCAL copy; num in main is untouched

From Problem Analysis to Program Design, 5e Page 11


Java Programming • Chapter 7: Methods In-Depth Study Guide

✔ Common misconception

Students sometimes expect num to become 16 after the call. It does not. Pass-by-value means
the method receives a copy, not a reference to the original.

6.3 Reference Variables as Parameters — type String


A String variable holds a reference (memory address) to a String object. When passed to a method, the
reference is copied — both the formal and actual parameter point to the same object. However, because String
is immutable, any operation that appears to 'change' a String (like pStr = "Sunny Day") actually creates a
new object and updates only the local formal parameter. The original variable in main() is unaffected.

public static void main(String[] args) {

String str = "Hello"; // str → 'Hello' object at addr 1500

stringParameter(str);

[Link](str); // still "Hello" — see explanation below

public static void stringParameter(String pStr) { // pStr = copy of addr 1500

// pStr currently points to 'Hello' (same object as str)

pStr = "Sunny Day"; // creates NEW object at addr 1800, pStr now points there

// str in main still points to addr 1500 ('Hello')

6.4 Reference Variables as Parameters — class StringBuffer


StringBuffer is mutable. When you call mutating methods like append() or delete() on the formal
parameter, you are modifying the actual underlying object in heap memory. The change IS visible back in the
caller after the method returns, because both the formal and actual parameter still refer to the same object.

public static void main(String[] args) {

StringBuffer str = new StringBuffer("Hello"); // str → object at addr 2000

stringBufferParameter(str);

[Link](str); // "Hello There" — the object was mutated!

From Problem Analysis to Program Design, 5e Page 12


Java Programming • Chapter 7: Methods In-Depth Study Guide

public static void stringBufferParameter(StringBuffer pStr) {

// pStr holds addr 2000 — same object as str

[Link](" There"); // modifies the object at addr 2000 in-place

// After return: str still points to addr 2000, which now contains 'Hello There'

Type What happens when you reassign the formal param inside
the method?

Primitive (int, double…) Only the local copy changes. Original variable is unaffected.

String (immutable reference) Reassignment creates a new object; original variable unaffected.

StringBuffer / arrays (mutable Mutation of the object IS visible in the caller.


reference)

From Problem Analysis to Program Design, 5e Page 13


Java Programming • Chapter 7: Methods In-Depth Study Guide

7. Scope of Identifiers
The scope of an identifier is the region of source code in which that identifier is visible (can be referenced).
Java's scope rules are block-based: an identifier declared inside a pair of curly braces {} is visible only within
those braces and in any nested blocks, from the point of declaration to the closing brace.

7.1 Local Identifiers


• A variable declared inside a method is a local variable. It is created when execution reaches the
declaration and destroyed when the method returns.
• A formal parameter is also a local variable — its scope is the entire method body.
• Java does not allow method definitions to be nested inside other methods.
• Within a method, an identifier declared in an outer block cannot be redeclared in an inner block — doing so
is a compile error.

public static void illegalIdentifierDeclaration() {

int x = 5;

double x = 3.14; // COMPILE ERROR: x already declared in enclosing scope

7.2 Class-Level (Static) Identifiers


Identifiers declared outside every method but inside the class body are class-level members. For static
methods:

• A static class-level identifier (e.g., static int z;) is accessible from any static method, unless a local
variable of the same name shadows it.
• A non-static class-level identifier (without static) cannot be accessed from a static method at all.

7.3 Scope Visibility Table (from Example 7-11)


Given the class structure from the slides:

class ScopeRules {

static final double rate = 10.50; // (a) visible everywhere

static int z; // (b) shadowed in main and method two

static double t; // (c) visible everywhere

From Problem Analysis to Program Design, 5e Page 14


Java Programming • Chapter 7: Methods In-Depth Study Guide

public static void main(String[] args) {

int num; double x, z; char ch; // local: visible only in main

public static void one(int x, char y) { ... }

public static int w; // (d) visible everywhere

public static void two(int one, int z) {

char ch; int a;

{ int x = 12; ... } // x visible only in this inner block

Identifier Visible in main? Visible in one? / two? / block three?

rate (static final) Yes Yes / Yes / Yes

z (class-level static) No — shadowed by local Yes / No — shadowed / No


z

t (static) Yes Yes / Yes / Yes

local vars of main Yes No / No / No

one (method name) Yes Yes / Yes / Yes

x (one's formal param) No Yes / No / No

w (declared before two) Yes Yes / Yes / Yes

one (two's formal param) No No / Yes / Yes

z (two's formal param) No No / Yes / Yes

x (block three local) No No / No / Yes

From Problem Analysis to Program Design, 5e Page 15


Java Programming • Chapter 7: Methods In-Depth Study Guide

8. Method Overloading
Java allows multiple methods in the same class to share the same name, provided they have different formal
parameter lists. The compiler selects the correct version at compile time based on the number and types of
the actual arguments — a mechanism called static polymorphism or compile-time binding.

8.1 Method Signature


A method's signature = its name + its formal parameter list (types and order). The return type is explicitly
not part of the signature. Two methods have different signatures if they have either different names or different
parameter lists.

8.2 Rules for Valid Overloading


• Different number of formal parameters, OR
• Same number but at least one corresponding type differs, OR
• Same number and types but in a different order.

// All four overloads are VALID — each has a unique signature

public void methodXYZ() { }

public void methodXYZ(int x, double y) { }

public void methodXYZ(double one, int y) { } // order differs from above

public void methodXYZ(int x, double y, char ch) { }

// Practical overloading example (like [Link])

public static int hi(int a, int b) { return a + b; }

public static int hi(int a, int b, int c) { return a + b + c; }

public static double hi(double a, double b) { return a + b; }

8.3 Invalid Overloading

// INVALID — return type alone does not differentiate signatures

public void methodABC(int x, double y) { }

public int methodABC(int x, double y) { } // COMPILE ERROR

// INVALID — parameter names do not matter, only types and order

From Problem Analysis to Program Design, 5e Page 16


Java Programming • Chapter 7: Methods In-Depth Study Guide

public void methodSix(int x, double y, char ch) { }

public void methodSix(int one, double u, char fCh) { } // same signature!

✔ Overloading resolution

If no exact type match exists, Java applies automatic widening conversion (e.g., int → long → float
→ double) to find the best match. If two overloads are equally good after widening, a compile-time
ambiguity error is raised.

From Problem Analysis to Program Design, 5e Page 17


Java Programming • Chapter 7: Methods In-Depth Study Guide

9. Debugging: Drivers, Stubs, and Incremental


Development
In large multi-method programs, bugs are far easier to isolate when methods are tested independently. Two
complementary techniques facilitate this: driver programs and method stubs.

9.1 Driver Programs


A driver is a small, temporary program whose sole purpose is to test a single method or a small set of related
methods. You write a main() that calls the target method with carefully chosen test inputs and verifies that the
outputs are correct before integrating the method into the full application.

// Driver for the larger() method

public class TestLarger {

public static void main(String[] args) {

[Link](larger(10.0, 20.0)); // expect 20.0

[Link](larger(7.5, 3.2)); // expect 7.5

[Link](larger(-1.0, -5.0)); // expect -1.0

[Link](larger(4.4, 4.4)); // expect 4.4 (equal case)

public static double larger(double x, double y) {

if (x >= y) return x;

return y;

9.2 Method Stubs


When a method A depends on the result of method B (which is not yet implemented), you cannot test A in
isolation. A stub is a minimal stand-in implementation of B that compiles and returns a plausible value, allowing
A to be tested now.

// Stub for a void method — just empty braces

public static void displayMenu() { }

// Stub for a value-returning method — return a hardcoded plausible value

public static double calculateTax(double income) {

From Problem Analysis to Program Design, 5e Page 18


Java Programming • Chapter 7: Methods In-Depth Study Guide

return 0.0; // stub: always returns 0, real logic added later

9.3 One-Piece-at-a-Time (Incremental) Development


• Decompose the problem into sub-problems until each piece has an obvious, straightforward
implementation.
• Implement one method at a time.
• Test it with a driver and stubs.
• Save a working version before adding the next piece.
• Integrate: once all methods pass their individual tests, assemble and run the complete program.
• Principle: a working program with fewer features is always better than a non-working program with many
features.

✔ Version control tip

Save each tested version with a clear name (e.g., v1_menu_only.java,


v2_conversion_added.java). If a later change breaks something, you can diff against the last
known-good version.

From Problem Analysis to Program Design, 5e Page 19


Java Programming • Chapter 7: Methods In-Depth Study Guide

10. Key Programming Exercises

10.1 Largest of 10 Numbers


Read 10 doubles from the user; use the value-returning method larger(double, double) to keep a
running maximum.

static Scanner console = new Scanner([Link]);

public static void main(String[] args) {

double num = [Link]();

double max = num; // initialise max with first input

for (int count = 1; count < 10; count++) {

num = [Link]();

max = larger(max, num); // update max each iteration

[Link]("The largest number is " + max);

public static double larger(double x, double y) {

return (x >= y) ? x : y;

// Sample output: enter 10.5 56.34 73.3 42 22 67 88.55 26 62 11

// The largest number is 88.55

10.2 Mean and Standard Deviation (Question 15)


For five numbers x1–x5, mean = (x1+x2+x3+x4+x5)/5 and standard deviation uses the formula from the slides.
The program must contain at least a mean() method and a standardDeviation() method.

public static double mean(double x1, double x2, double x3,

double x4, double x5) {

return (x1 + x2 + x3 + x4 + x5) / 5.0;

public static double standardDeviation(double x1, double x2, double x3,

From Problem Analysis to Program Design, 5e Page 20


Java Programming • Chapter 7: Methods In-Depth Study Guide

double x4, double x5) {

double m = mean(x1, x2, x3, x4, x5);

double sumSq = [Link](x1-m,2) + [Link](x2-m,2) + [Link](x3-m,2)

+ [Link](x4-m,2) + [Link](x5-m,2);

return [Link](sumSq / 5.0);

10.3 Menu-Driven Unit Converter


Three methods: showChoices() (void, prints menu), inchesToCentimeters(double) (value-returning),
centimetersToInches(double) (value-returning). Loop until user chooses Exit (3).

public static void showChoices() {

[Link]("Menu:");

[Link](" 1. In to Cm");

[Link](" 2. Cm to In");

[Link](" 3. Exit");

public static double inchesToCentimeters(double inches) { return inches * 2.54;


}

public static double centimetersToInches(double cm) { return cm / 2.54; }

// In main — loop until user picks 3:

int choice;

do {

showChoices();

choice = [Link]();

if (choice == 1) { ... }

else if (choice == 2) { ... }

} while (choice != 3);

10.4 mult() Function (Exercise 1)

// Accepts two ints, returns their product

public static int mult(int a, int b) {

return a * b;

From Problem Analysis to Program Design, 5e Page 21


Java Programming • Chapter 7: Methods In-Depth Study Guide

From Problem Analysis to Program Design, 5e Page 22


Java Programming • Chapter 7: Methods In-Depth Study Guide

11. Exam-Ready Reference Tables

11.1 Full Chapter Concept Summary


Concept Technical Definition & Key Points

Method A named block of code inside a class. Declared with: modifiers returnType
name(params){body}. Promotes reuse, readability, and testability.

Predefined method Methods provided by the Java standard library. Accessed via class name
(e.g., [Link]) or via static import.

Value-returning method Return type ≠ void. Must have a return expr; on every code path. Called
inside an expression.

void method Return type = void. Performs side effects. Called as a standalone
statement. Can use bare return; to exit early.

Formal parameter Variable declared in the method header. Receives the value/reference of
the actual parameter at call time. Acts as a local variable inside the method.

Actual parameter Expression in the method call that supplies the value for the corresponding
formal parameter. Must be type-compatible.

Pass-by-value (primitive) A COPY of the value is passed. Changes to the formal parameter inside the
method do NOT affect the original variable.

Pass-by-value (reference) A COPY of the reference (address) is passed. Mutations of the object via
the formal parameter ARE visible to the caller. Reassigning the formal
parameter is NOT.

String parameter Immutable. Reassigning pStr inside a method creates a new object; caller's
variable unchanged.

StringBuffer parameter Mutable. append/delete mutate the shared object; changes visible to caller.

Local identifier Declared inside a method or block. Visible only within that block and nested
blocks, from declaration to closing brace.

Scope shadowing A local variable with the same name as a class-level variable hides the
class-level one within its scope.

Method signature name + parameter list (types and order). Return type is NOT part of the
signature.

Method overloading Multiple methods in the same class share a name but have different
signatures. Resolved at compile time (static polymorphism).

Driver program A small test harness that calls a specific method with test inputs to verify
correctness in isolation.

From Problem Analysis to Program Design, 5e Page 23


Java Programming • Chapter 7: Methods In-Depth Study Guide

Concept Technical Definition & Key Points

Method stub An incomplete placeholder method (correct header, minimal body) that
allows compilation and partial testing while the real implementation is
pending.

Top-down / Decompose a large problem into sub-problems; implement and test one
divide-and-conquer piece at a time; integrate when all pieces work.

11.2 Math Class Quick Reference


Method Returns Notes

[Link](x) Same type as x int/long/float/double overloads

[Link](x) double x must be ≥ 0; x is double

[Link](x,y) double Both params must be double

[Link](x) long (or int) Nearest integer; 0.5 rounds up

[Link](x) double Rounds UP; x is double

[Link](x) double Rounds DOWN; x is double

[Link](x,y) Same type as args 4 overloads

[Link](x,y) Same type as args 4 overloads

[Link](x) double Natural log (base e)

Math.log10(x) double Common log (base 10)

[Link]/cos/tan double Argument in radians

[Link]() double In range [0.0, 1.0)

[Link] double constant 3.141592653589793

Math.E double constant 2.718281828459045

End of Chapter 7 In-Depth Study Guide — Good luck!

From Problem Analysis to Program Design, 5e Page 24

You might also like