Java Methods are blocks of code that can be used to perform specific operations within a Java program. They provide an efficient way for developers to create reusable functions which can then be called from anywhere in the application allowing for more
DRY code and improved readability. This allows any changes made to the method’s logic, such as bug fixes or new features, to propagate throughout the entire project without having duplicate pieces of identical source code cluttering up one’s workspace.
Java provides several types of methods, including
● Instance methods: These methods are associated with an instance of a class and can access the state of the object. They are declared with the keyword "void" or with a return type.
● Static methods: These methods are associated with a class and can be called without creating an instance of the class. The keyword "static" is used to declare the static methods.
● Constructor methods: The Constructor methods are used to create and initialize an object. They are declared with the same name as the class and are invoked using the keyword "new".
Instance method example:
class MyClass {
int a;
int b;
public void assignValues(int a, int b) {
this.a = a;
this. b = b;
}
}
This class has an instance method called assignValues, which takes two parameters and assigns them to the instance variables a and b.
Static method example:
class MyClass {
static int x;
static int y;
public static void setValues(int x, int y) {
MyClass.x = x;
MyClass.y = y;
}
}
This class has a static method called setValues, which takes two parameters and assigns them to the static variables x and y
Constructor method example:
class MyClass {
int x;
int y;
public MyClass(int x, int y) {
this.x = x;
this.y = y;
}
}
This class has a constructor method with the same name as the class, which takes two parameters and assigns them to the instance variables x and y.
The method also returns values, look at the example below:
public int add(int x, int y) {
return x + y;
}
This method takes two integers as a parameter and returns the sum of those integers.