Java Methods
In Java, a method is a block of code that performs a specific task. Methods are used to modularize code, which makes it easier to read, maintain, and reuse.
Java Declaring a Method
In Java, you declare a method using the following syntax:
[access modifier] [static] [final] [return type] [method name]([parameter list]) {
// method body
}
Here's a breakdown of each part of the method declaration:
- Access modifier: determines the visibility of the method. There are four access modifiers in Java:
public,protected,private, and default (no access modifier specified). - Static: specifies whether the method is associated with the class (
statickeyword) or with an instance of the class (nostatickeyword). - Final: specifies that the method cannot be overridden by subclasses.
- Return type: specifies the type of value returned by the method. If the method does not return a value, use the keyword
void. - Method name: specifies the name of the method.
- Parameter list: specifies the parameters passed to the method. Multiple parameters are separated by commas.
Here's an example of a method declaration:
public static void printMessage(String message) {
System.out.println(message);
}
In this example, the method is called printMessage and takes a single argument of type String called message. The method body simply prints the message to the console using the System.out.println method.
Java Calling a Method
To call this method from another part of the code, you can use its name and pass the argument(s) it requires:
printMessage("Hello, world!");
This will print the message "Hello, world!" to the console.
Java method types
Java supports several types of methods, including:
- Instance methods: methods that operate on an instance of a class and can access the instance variables and methods of that class.
- Static methods: methods that are associated with a class and can be called without creating an instance of that class.
- Constructors: special methods that are called when an object is created and are used to initialize the object's properties.
- Getters and setters: methods used to read and modify the properties of an object.
return value
Methods can also return a value using the return keyword. Here's an example:
public static int addNumbers(int a, int b) {
int sum = a + b;
return sum;
}
This method takes two integers as arguments, adds them together, and returns the result as an integer. To use this method and capture the return value:
int result = addNumbers(3, 4); System.out.println(result); // prints 7
This code calls the addNumbers method with arguments 3 and 4, captures the return value in the result variable, and then prints the value to the console.
