Curriculum
In Java, a method is a block of code that performs a specific task and can be called from other parts of the program. It can have input parameters and return a value, or it can be a void method that doesn’t return anything. Methods are defined inside classes, and can be accessed and called from objects of that class.
To define a method in Java, you use the following syntax:
<access modifier> <return type> <method name>(<parameter list>) { // method body // return statement (if applicable) }
Here, the access modifier specifies the level of access to the method (public, private, protected, or default), the return type specifies the type of value returned by the method (or “void” if it doesn’t return anything), the method name is a unique identifier for the method, and the parameter list is a comma-separated list of input parameters for the method.
Here’s an example of a simple method that takes two integers as input and returns their sum:
public int add(int a, int b) { int sum = a + b; return sum; }
This method has the public access modifier, returns an integer value, and takes two integer parameters named “a” and “b”. The method body defines a local variable “sum” that holds the sum of the two parameters, and then returns this value.
To call this method from another part of the program, you create an instance of the class containing the method and use the dot notation to access the method, like this:
MyClass myObject = new MyClass(); int result = myObject.add(2, 3); System.out.println(result); // prints 5
Here, “MyClass” is the name of the class that contains the “add” method, “myObject” is an instance of this class, and “result” is a variable that holds the return value of the “add” method.
Methods in Java are used to encapsulate logic and functionality into reusable units of code, making it easier to organize and maintain the program. They can be used for a variety of tasks, such as calculations, data manipulation, input/output operations, and more. Java also provides a set of built-in methods for common tasks, such as string manipulation, array handling, and math operations, which can be used without having to define them yourself.