Function
In Java, functions are known as methods. A method is a block of code that performs a specific task and can be called from other parts of the program. Methods are used for code reusability and organization. Here's how you define and use methods in Java:
Method Declaration:
In Java, a method is declared within a class. The basic syntax of a method declaration looks like this:
access_modifier return_type method_name(parameter_list) {
// Method body
// Code to be executed
return value; // Return statement (if the method returns a value)
}access_modifier: Specifies the visibility of the method (public,private,protected, or package-private).return_type: Specifies the data type of the value the method returns. Usevoidif the method doesn't return any value.method_name: Specifies the name of the method.parameter_list: Specifies the parameters the method accepts (if any).return value: Specifies the value to be returned by the method (if applicable).
Example of a Method:
public class Example {
// Method that takes two integers as parameters and returns their sum
public int addNumbers(int a, int b) {
int sum = a + b;
return sum;
}
public static void main(String[] args) {
Example example = new Example();
int result = example.addNumbers(5, 10);
System.out.println("Sum: " + result);
}
}Explanation:
public int addNumbers(int a, int b) { ... }: This line declares a method namedaddNumberswith two integer parameters (aandb). The method returns an integer (int). Inside the method, the two parameters are added, and the sum is stored in thesumvariable. The method then returns thesum.Example example = new Example();: Creates an instance of theExampleclass.int result = example.addNumbers(5, 10);: Calls theaddNumbersmethod of theexampleobject with the arguments5and10. The returned sum (15in this case) is stored in theresultvariable.System.out.println("Sum: " + result);: Prints the result, which is15, to the console.
When you run this Java program, it will output:
Sum: 15This output shows the result of calling the addNumbers method with the arguments 5 and 10. The method calculated the sum and returned the value 15, which was then printed in the main method.
Last updated