Java functions
Created By: chatGPT
In Java, functions are defined in the form of methods. A method is a collection of statements that performs a specific task. You can define methods in classes, and they can accept parameters and return values. Below are the key components of a method in Java.
A method declaration consists of the following components:
- Return Type: Specifies the type of value the method returns. If the method does not return a value, the return type is
void
. - Method Name: A descriptive name that indicates what the method does.
- Parameters: Optional inputs to the method, defined in parentheses.
- Method Body: The block of code that defines what the method does, enclosed in braces
{}
.
Here’s a simple example of a method that adds two integers and returns the sum:
public int add(int a, int b) {
return a + b;
}
You can call this method from another method or the
main
method in Java. Below is an example of how to call the add
method:public static void main(String[] args) {
MyClass obj = new MyClass();
int sum = obj.add(5, 10);
System.out.println("Sum: " + sum);
}
You can also define methods without parameters and return values. Here’s an example of a method that prints a message:
public void printMessage() {
System.out.println("Hello, World!");
}
To call this method, you can use the following code in the
main
method:public static void main(String[] args) {
MyClass obj = new MyClass();
obj.printMessage();
}
Furthermore, methods can be overloaded in Java, meaning you can have multiple methods with the same name but different parameters. Here’s an example of method overloading with the
When you call the add
method:public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
add
method, Java determines which version to use based on the argument types you pass. Thus, performing operations on different data types is seamless and enhances code reusability.