Methods
Java methods are blocks of code that are only executed when the specific method is called. Methods are extremely useful tools to reuse code or break down a large task into smaller chunks. Methods can accept a few parameters and return an object as well.
There are two types of methods:
-
User-defined Methods: methods we can to perform specific tasks
-
Standard Library Methods: methods included in Java libraries
User-Defined Methods
accessModifier returnType methodName() {
// method content
}
accessModifier: the access type of the method, generally public
or private
returnType: defines the type of the value that the method will return
methodName: the name of the method, which should be descriptive of the task or operation that the method is performing
method content: the content and operations included within the method
Standard Library Methods
Standard library methods are built-in and they are embedded within the Java class.
A few examples:
print() // from java.io.PrintStream
sqrt() // from the Math class
Examples
Example Program Using Methods
public class Calculator {
public static int doubleIt(int num) {
return num * 2;
}
}
public class MyConsole {
public static void main(String[] args) {
// initialize a variable, and then print the variable doubled
int value = 4;
int doubledValue = Calculator.doubleIt(value);
System.out.println("The double of " + value + " is " + doubledValue + ".");
}
}
Output:
The double of 4 is 8.