Unit 2: Java Basics
Methods, or functions, are the building blocks of organized code. They allow you to bundle a specific task into a reusable, named block, making your programs more modular, readable, and easier to debug.
As programs grow, you'll find yourself performing the same tasks repeatedly. Instead of copying and pasting code, you can define a method. This approach is essential for writing professional-quality code.
Every method in Java has a "signature" that defines its properties. This signature tells the compiler what the method is called, what kind of data it needs, and what kind of data it will return.
public static int calculateScore(int currentScore, int pointsToAdd) {
int newScore = currentScore + pointsToAdd;
return newScore;
}
These terms are often used interchangeably, but they have distinct meanings:
A method can perform a calculation and send a result back to the code that called it. This is called a "return value." The `return` keyword is used to send this value back and immediately exit the method.
If a method is not meant to return any value, its return type is declared as `void`.
// A method that returns a value
public static double getAverage(double a, double b) {
return (a + b) / 2.0;
}
// A method that performs an action but returns nothing (void)
public static void printWarning(String message) {
System.out.println("WARNING: " + message);
}
// Calling the methods
double avg = getAverage(10.0, 20.0); // avg is now 15.0
printWarning("Sensor offline!"); // Prints a message to the console
Question: Given the method signature `public boolean isMotorAtLimit()`, what type of value does this method return?