Module 4: Method basics Flashcards
What is a method?
A block of code used to perform a task and only runs when you call it. Methods only need to be written once. A method must be declared in a class.
Ex creating:
public void method() {}
Ex calling:
method();
What are method parameters?
Code inside their parentheses which act like variables inside the method. They can take multiple parameters, separate them by a comma. Parameters passed to a method are called “arguments”.
Ex creating:
public void default(int A, double B) {}
Ex calling:
default(11, 20.5);
Note if you use multiple parameters, when you call the method it must have the same number of arguments as there is parameters, and the arguments must be passed in the same order.
What is a return type?
When you want a method to return a value, use a primitive data type before the method name, then use a return keyword inside.
Ex:
static double percent(double num, int percentage) {double res = num*percentage/100; return res;}
It is good practice to store a returned result from a method in a variable.
What does the void keyword do?
Specifies a method should not have a return value.
Ex:
public void method() {}