Java Methods
What methods are
A method is a named block of statements you can run from elsewhere in the program. You have already called methods such as System.out.println() and Integer.valueOf().
Splitting work into methods keeps each part small, makes bugs easier to find, and lets you reuse the same logic in several places.
Method structure
// Basic method structure
public static void methodName() {
// Method body - code to execute
System.out.println("This method does something!");
}
// Method with parameters
public static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
// Method that returns a value
public static int addNumbers(int a, int b) {
return a + b;
}
// Method placement in a class
public class RobotProgram {
public static void main(String[] args) {
// Call methods from main
greet("Robot");
int result = addNumbers(5, 3);
System.out.println("Sum: " + result);
}
// Methods go here, outside of main but inside the class
public static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
public static int addNumbers(int a, int b) {
return a + b;
}
}Method Parameters
Parameters are variables listed in the method header. When you call the method, the argument values are copied into those parameters for the duration of the call.
Single parameter
// Method with one parameter
public static void setMotorPower(double power) {
System.out.println("Setting motor power to: " + power);
// Code to actually set motor power would go here
}
// Calling the method
public static void main(String[] args) {
setMotorPower(0.5); // Pass 0.5 as the power value
setMotorPower(1.0); // Pass 1.0 as the power value
// You can also pass expressions
double targetPower = 0.75;
setMotorPower(targetPower); // Pass variable value
setMotorPower(0.25 + 0.25); // Expression evaluates to 0.5
}Multiple parameters
// Method with multiple parameters
public static void driveRobot(double forward, double strafe, double rotate) {
System.out.println("Drive command - Forward: " + forward +
", Strafe: " + strafe + ", Rotate: " + rotate);
// Robot driving code would go here
}
// Method that calculates and returns a value
public static double calculateDistance(double x1, double y1, double x2, double y2) {
double deltaX = x2 - x1;
double deltaY = y2 - y1;
return Math.sqrt(deltaX * deltaX + deltaY * deltaY);
}
// Calling methods with multiple parameters
public static void main(String[] args) {
// Parameters are passed in the same order as defined
driveRobot(0.8, 0.0, 0.2); // forward=0.8, strafe=0.0, rotate=0.2
// Calculate distance between two points
double dist = calculateDistance(0, 0, 3, 4);
System.out.println("Distance: " + dist); // Output: 5.0
}Method Call Stack
Each method call gets its own stack frame for local variables. When a method returns, that frame is popped and execution continues in the caller.
Call stack example
public static void main(String[] args) {
System.out.println("Starting main method");
startRobot(); // Call startRobot method
System.out.println("Back in main method");
}
public static void startRobot() {
System.out.println("Robot starting...");
initializeSensors(); // Call initializeSensors method
System.out.println("Robot ready!");
}
public static void initializeSensors() {
System.out.println("Initializing sensors...");
System.out.println("Sensors ready!");
}
/* Output:
Starting main method
Robot starting...
Initializing sensors...
Sensors ready!
Robot ready!
Back in main method
Call stack visualization:
1. main() starts
2. main() calls startRobot() - stack: [main, startRobot]
3. startRobot() calls initializeSensors() - stack: [main, startRobot, initializeSensors]
4. initializeSensors() finishes - stack: [main, startRobot]
5. startRobot() finishes - stack: [main]
6. main() finishes - program ends
*/Basic method examples
public class Calculator {
// Method that returns a value
public int add(int a, int b) {
return a + b;
}
// Method that doesn't return a value (void)
public void printResult(int result) {
System.out.println("Result: " + result);
}
// Method with no parameters
public void sayHello() {
System.out.println("Hello!");
}
}Method Naming Conventions
Name methods with camelCase verbs (initializeSensors, not doStuff). Indent the method body by four spaces.
Good vs bad method names
// [ERROR] BAD: Poor naming conventions
public static void This_method_says_woof ( ) {
System.out.println("woof");
}
public static void doStuff() {
// What does this do?
}
public static void x() {
// Too short, unclear
}
// [OK] GOOD: Proper naming conventions
public static void thisMethodSaysWoof() {
System.out.println("woof");
}
public static void initializeRobotSensors() {
System.out.println("Initializing all robot sensors...");
// Clear purpose, proper camelCase
}
public static void calculateMotorPower() {
// Descriptive name, proper indentation
double power = 0.5;
System.out.println("Motor power: " + power);
}Parts of a method header
- public static: visibility and whether the method belongs to the class (common in lesson examples)
- Return type:
void,int,double,String,boolean, etc. - Name: camelCase verb
- Parameters:
(type name, ...)in the parentheses - Body: statements inside
{ }, indented four spaces
Methods calling other methods
One method can call another. Each call pushes a new frame onto the stack.
public class RobotController {
public static void main(String[] args) {
System.out.println("Starting robot program...");
runAutonomousMode();
System.out.println("Program complete!");
}
public static void runAutonomousMode() {
System.out.println("Autonomous mode starting...");
initializeRobot();
executeMovementSequence();
System.out.println("Autonomous mode complete!");
}
public static void initializeRobot() {
System.out.println("Initializing robot systems...");
initializeSensors();
initializeMotors();
System.out.println("Robot ready!");
}
public static void initializeSensors() {
System.out.println("- Sensors initialized");
}
public static void initializeMotors() {
System.out.println("- Motors initialized");
}
public static void executeMovementSequence() {
moveForward(24); // Move 24 inches forward
turnRight(90); // Turn 90 degrees right
moveForward(12); // Move 12 inches forward
}
public static void moveForward(double inches) {
System.out.println("Moving forward " + inches + " inches");
}
public static void turnRight(double degrees) {
System.out.println("Turning right " + degrees + " degrees");
}
}
/* Output:
Starting robot program...
Autonomous mode starting...
Initializing robot systems...
- Sensors initialized
- Motors initialized
Robot ready!
Moving forward 24.0 inches
Turning right 90.0 degrees
Moving forward 12.0 inches
Autonomous mode complete!
Program complete!
*/The Main Method
main is the entry point: the JVM calls public static void main(String[] args) first. Other methods are reached from main or from methods main calls.
Try It Yourself:
Exercise 1: Method Fundamentals
- Create a simple greet method and call it multiple times
- Build a method with parameters that prints robot status
- Write a method that returns a calculated value
- Create a complex method that calls other methods
Practice creating and calling methods: