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
: Specifies the visibility of the method (public
,private
,protected
, or package-private).return_type
: Specifies the data type of the value the method returns. Usevoid
if 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:
Explanation:
public int addNumbers(int a, int b) { ... }
: This line declares a method namedaddNumbers
with two integer parameters (a
andb
). The method returns an integer (int
). Inside the method, the two parameters are added, and the sum is stored in thesum
variable. The method then returns thesum
.Example example = new Example();
: Creates an instance of theExample
class.int result = example.addNumbers(5, 10);
: Calls theaddNumbers
method of theexample
object with the arguments5
and10
. The returned sum (15
in this case) is stored in theresult
variable.System.out.println("Sum: " + result);
: Prints the result, which is15
, to the console.
When you run this Java program, it will output:
This 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