Methods are also called functions or subroutines. All three names are synonymous.
what? Pieces of code that are in a code block that does a specific function
why?
[modifiers] [return value] [function name] ( [arguments] ) { [statements] }
Example:
static int square(int x) { return x*x; }This method is called square. It takes one number that is an int. It returns an int. For now, we'll just ignore the modifiers. The most common ones are private, public, and static.
1. must start with lowercase (use camelCase)
2. recommended to start with a verb. e.g. getInput()
double x = Math.sin(Math.PI/3); System.out.print("stuff");
Note that the parameters in a method header are local variables.
This means that their names have no relation to any other variable name in the program. (See the section on scope of variables **insert link**)
The variables are created in the method header and they are destroyed when the final } ends the method
The critical thing about parameters is their order and type
Have a look at the program below. (To run it you'd have to make both methods static)
void method1() { String fruit = "cherry"; String store = "The Bay"; int favNumber = 20161024; method2(store, fruit, favNumber); //we don't have to do anything with the boolean that is returned boolean result = method2("Mr. Smith", store, myStaticInt); if (result) System.out.println("oops. Bye \"" + store + "\""); } boolean method2(String assassin, String target, int date) { boolean success; //ERROR: local variables MUST be initialized. success = false; System.out.println("The target is " + target); if (assassin.equals("Mr. Smith")) success=true; return success; }