In Java, a method is a block of code that performs a specific task and is defined within a class. A function is a block of code that performs a specific task and is defined outside of a class.
In Java, methods and functions are similar in that they both contain a block of code that can be called and executed by other parts of the program. However, there are some differences between methods and functions in Java:
Scope: Methods are defined within a class and have access to the variables and other members of that class, while functions are defined outside of a class and do not have access to the variables and members of any particular class.
Declaration: Methods are declared within a class using the public
, private
, or protected
access modifiers and a return type, while functions are declared outside of a class using a return type and the static
modifier.
Invocation: Methods are invoked on an instance of a class using the .
operator, while functions are invoked by their name.
Here is an example of a method in Java:
public class MyClass { public void sayHello() { System.out.println("Hello, World!"); } }
This method, sayHello
, is defined within the MyClass
class and can be invoked on an instance of MyClass
like this:
MyClass myObject = new MyClass(); myObject.sayHello();
Here is an example of a function in Java:
public static int add(int x, int y) { return x + y; }
This function, add
, is defined outside of any class and can be invoked by its name like this:
int result = add(3, 4);
For more information on methods and functions in Java, you can refer to the Java documentation or other online resources.