In Java programming, a method is a collection of statements that perform a specific task. When you want to execute a method, you need to call it within your program. Here’s how you can call a method in Java:
1. Call a Method from the Same Class
If the method you want to call is in the same class where you are calling it, you can simply use the method name followed by parentheses. For example:
public class MyClass {
void myMethod() {
System.out.println("Calling myMethod");
}
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.myMethod();
}
}
When you run the code, it will output: Calling myMethod
2. Call a Method from Another Class
If the method you want to call is in another class, you need to create an instance of that class and then call the method using the instance. Here’s an example:
public class AnotherClass {
void anotherMethod() {
System.out.println("Calling anotherMethod");
}
}
public class Main {
public static void main(String[] args) {
AnotherClass obj = new AnotherClass();
obj.anotherMethod();
}
}
When you run this code, it will output: Calling anotherMethod
These are the basic steps to call a method in Java. By understanding how to call methods, you can create more organized and efficient programs in Java.