Java Programming
Chapter 7 – Methods
Student Study Guide
Beginner-Friendly Summary
1. What is a Method?
A method is a named block of code that performs a specific task. Instead of writing the same
code over and over, you write it once inside a method and then call (use) it whenever you need
it.
Why use methods?
• Focus: You can build and fix one small piece of code at a time, making it much easier to
find bugs.
• Teamwork: Multiple programmers can each work on different methods at the same time.
• Reuse: If the same task is needed in several places, you write the method once and call
it many times.
• Readability: The main() method stays short and easy to read because complex logic
lives in separate methods.
Real-life analogy
Think of a method like a coffee machine. You press a button (call the method) and it does the
complicated work for you (brewing). You don't need to know how it works inside — you just use the
result.
2. Predefined (Built-in) Methods
Java comes with thousands of ready-made methods that you can use right away. These are
organized inside classes in packages.
The Math Class ([Link])
The Math class provides common mathematical operations. Since it is in [Link], it is
automatically available.
Method Example What it does
[Link](x) [Link](-5) = 5 Returns the positive (absolute) value
[Link](x) [Link](9) = 3.0 Returns the square root
[Link](x,y) [Link](2,3) = 8.0 Returns x raised to the power y
[Link](x) [Link](3.7) = 4 Rounds to the nearest integer
[Link](x,y) [Link](5,10) = 10 Returns the larger of two values
[Link](x,y) [Link](5,10) = 5 Returns the smaller of two values
[Link](x) [Link](4.9) = 4.0 Rounds DOWN to the nearest whole number
[Link](x) [Link](4.1) = 5.0 Rounds UP to the nearest whole number
Static Import Shortcut
Normally you write [Link](4.0). Using a static import, you can just write sqrt(4.0):
import static [Link].*;
// Now you can write:
double result = sqrt(4.0); // instead of [Link](4.0)
double power = pow(2.5, 3.5);
The Character Class ([Link])
The Character class has useful methods for working with single characters (type char):
• [Link]('a') → true (checks if lowercase)
• [Link]('A') → true (checks if uppercase)
• [Link]('D') → 'd' (converts to lowercase)
• [Link]('j') → 'J' (converts to uppercase)
3. Value-Returning Methods
A value-returning method does some work and then sends a result back to where it was called
from. Think of it like asking a question and getting an answer.
Structure / Syntax
modifier(s) returnType methodName(formal parameter list)
{
// code that does the work
return someValue;
}
Real Example: Finding the Larger Number
public static double larger(double x, double y)
{
if (x >= y)
return x; // sends x back to the caller
else
return y; // sends y back to the caller
}
To use (call) this method you write:
double big = larger(23.50, 37.80); // big becomes 37.80
double big2 = larger(num1, num2); // works with variables too
Breaking Down the Parts
Part Meaning
public static Modifiers – control access and how the method is used
double Return type – the type of value the method sends back
larger Method name – what you call it by
double x, double y Formal parameters – the inputs the method needs
return x; Return statement – sends the answer back to the caller
4. Void Methods
A void method performs an action but does NOT send back a value. It just does something —
like printing to the screen or updating a variable. You use the keyword void instead of a return
type.
Syntax
modifier(s) void methodName(formal parameter list)
{
// code that does the action
// no return statement needed (or use 'return;' to exit early)
}
Example: Printing Hello World
public static void doSomething1() {
[Link]("Hello ");
}
public static void doSomething2() {
[Link]("World!");
}
// In main:
doSomething1(); // prints: Hello
doSomething2(); // prints: World!
Value-Returning vs Void – Quick Comparison
Value-returning: Use when you need a result to use later (e.g., calculate and return a number). Call it
inside an expression like: double x = larger(a, b); Void: Use when you just need to do something
(e.g., print output). Call it as a standalone statement like: printResults();
5. Flow of Execution
Understanding how Java runs your code is key to understanding methods:
• Java always starts executing from the first line of main().
• When Java reaches a method call, it pauses main() and jumps to that method.
• The method runs completely, then control returns back to where the call was made in
main().
• This repeats for every method call encountered.
Visual Flow Example
public static void main(String[] args) {
doSomething1(); // 1) jumps to doSomething1
doSomething2(); // 3) then jumps to doSomething2
doSomething3(); // 5) then jumps to doSomething3
} // 7) program ends
public static void doSomething1() { /* 2) runs here */ }
public static void doSomething2() { /* 4) runs here */ }
public static void doSomething3() { /* 6) runs here */ }
6. Parameters: Formal vs Actual
Parameters are how you pass information into a method.
Type Where it appears Example
Formal parameter In the method definition (declares double larger(double x, double
what the method expects) y) — x and y are formal
Actual parameter In the method call (the real values larger(23.50, 37.80) — 23.50
you pass in) and 37.80 are actual
Primitive vs Reference Parameters
How a parameter behaves inside a method depends on its type:
Primitive Types (int, double, char, etc.) — One-Way Copy
When you pass a primitive value, Java copies the value into the formal parameter. Changing the
formal parameter inside the method does NOT change the original variable.
// The original 'num' stays unchanged after calling this method
public static void addTen(int x) {
x = x + 10; // only changes the local copy, not the original
}
Reference Types (String, StringBuffer, arrays) — Shared Object
When you pass a reference variable, both the formal and actual parameter point to the SAME
object in memory. Changes to the object (like appending to a StringBuffer) ARE reflected
outside the method.
StringBuffer str = new StringBuffer("Hello");
stringBufferParameter(str);
// str is now "Hello There" because the method changed the same object!
public static void stringBufferParameter(StringBuffer pStr) {
[Link](" There"); // modifies the shared object
}
String vs StringBuffer — Important Difference!
String objects are IMMUTABLE (cannot be changed). Reassigning pStr = "Sunny Day" inside a
method creates a new object — the original str variable still points to "Hello". StringBuffer objects are
MUTABLE (can be changed). Using [Link]() modifies the actual object, so the change is visible
outside the method.
7. Scope of Identifiers
Scope means: where in your code can you see and use a variable? Think of it like a room — a
variable declared inside one room (block) can't be seen in another room.
Key Scope Rules
• A local variable declared inside a method is only visible within that method.
• A variable declared inside a block {} is only visible within that block and any blocks
nested inside it.
• A static variable declared outside all methods (at class level) with static is accessible
from any static method in the class, unless the method has its own variable with the
same name.
• You CANNOT nest method definitions — one method cannot be defined inside another.
• You CANNOT re-declare a variable in an inner block if the outer block already has a
variable with the same name.
Illegal Redeclaration Example
public static void illegalExample() {
int x = 5;
{
double x = 3.14; // ERROR! x is already declared in the outer block
}
}
8. Method Overloading
Method overloading means creating multiple methods with the same name but different
parameter lists. Java figures out which one to call based on the arguments you pass.
What makes a method unique? (The Signature)
A method's signature = its name + its parameter list (types and order). The return type is NOT
part of the signature.
Valid Overloading Examples
public static int hi(int a, int b) {
return a + b;
}
public static int hi(int a, int b, int c) { // different number of params
return a + b + c;
}
public static double hi(double a, double b) { // different param types
return a + b;
}
Invalid Overloading Example
public void methodABC(int x, double y) { }
public int methodABC(int x, double y) { } // ERROR! Same signature,
// only return type differs
Why use overloading?
Overloading lets you use the same intuitive method name for related operations. For example,
[Link]() works on int, long, float, and double — Java automatically picks the right version based on
the type you pass in.
9. Debugging: Drivers and Stubs
When building a large program with many methods, you shouldn't wait until everything is
finished to test it. Use drivers and stubs to test piece by piece.
Driver Programs
A driver is a small, temporary program written specifically to test a single method. You write a
mini main() that calls your method with test values to verify it works correctly before using it in
the full program.
Method Stubs
A stub is a placeholder for a method you haven't written yet. It has the correct method signature
but minimal code inside — just enough so the program compiles and runs.
• For a void stub: just the method header and empty braces { }
• For a value-returning stub: return a simple plausible value like return 0; or return "";
One-Piece-at-a-Time Approach (Top-Down Design)
The best way to build complex programs is to break the problem into smaller subproblems,
solve each one, test it, then combine them. This is called top-down design or divide and
conquer.
• Code and test one method at a time.
• Save working versions as you go.
• A working program with fewer features is better than a non-working one with many
features.
10. Key Exercises from the Slides
Exercise: Largest Number Program
Reads 10 numbers and prints the largest using a value-returning method larger():
num = [Link]();
max = num;
for (count = 1; count < 10; count++) {
num = [Link]();
max = larger(max, num); // keeps track of the biggest seen so far
}
[Link]("The largest number is " + max);
Exercise: Mean and Standard Deviation (Question 15)
Write a program that takes 5 numbers and computes both the mean (average) and standard
deviation using separate methods: one for mean, one for standard deviation.
Exercise: Menu-Driven Unit Converter
Create a program with 3 methods: showChoices() to display the menu, inchesToCentimeters()
and centimetersToInches(). The menu loops until the user selects Exit.
Menu:
1. In to Cm
2. Cm to In
3. Exit
Exercise: mult() Function (Exercise 1)
Write a method named mult() that accepts two int parameters, multiplies them, and returns the
result:
public static int mult(int a, int b) {
return a * b;
}
Quick Reference Summary
Concept Key Point
Method A named block of code that performs a specific task
Predefined method Already written by Java ([Link], [Link], etc.)
Value-returning Has a return type (int, double, etc.) and uses 'return value;'
Void method Has no return value; performs an action only
Formal parameter Variable in the method definition that receives a value
Actual parameter The real value passed when calling the method
Primitive param A copy is passed — original is unchanged
Reference param The same object is shared — changes may be visible outside
Scope Where a variable can be accessed in your code
Overloading Same method name, different parameter list
Driver A test program used to verify one method works correctly
Stub A placeholder method to allow compilation during development
Good luck on your studies! You've got this.