Sub topic 1
Declare and Call a Method
A method is a named set of instructions. You can call a method to run those instructions whenever you need them. Methods help you give a task a clear name and reuse its steps.
Declare and Call a Method
This program declares two methods, add and greet, then calls them from main.
public class MethodsDemo {
static int add(int left, int right) {
return left + right;
}
void greet(String name) {
System.out.println("Hello, " + name);
}
public static void main(String[] args) {
int total = MethodsDemo.add(2, 3);
MethodsDemo demo = new MethodsDemo();
demo.greet("Ava");
System.out.println(total);
}
}Save the code in a file named MethodsDemo.java. Then compile and run it:
javac MethodsDemo.java
java MethodsDemoThe output is:
Hello, Ava
5Java starts the program in the main method. It calls add, calls greet, and then prints the total.
Pass Arguments to Parameters
A parameter is a named input in a method declaration. The add method has two parameters: left and right. Their type, int, means they hold whole numbers.
An argument is a value supplied in a method call. In add(2, 3), the arguments are 2 and 3. The method receives them as left and right.
The greet method has one parameter, name. Its type, String, means it holds text. The call greet("Ava") passes the text "Ava" to it.
Return Results or Use void
A return type says what kind of value a method sends back. The return type of add is int. Its return statement sends the sum back to the call, where it is stored in total.
The return type of greet is void. That means it sends no value back. It prints a message instead. Printing shows text to the user; returning passes a value back to the caller.
Call Static and Instance Methods
A class is a blueprint for objects. An object is a particular thing created from a class.
A static method belongs to the class, so you can call it without creating an object. The example calls MethodsDemo.add(2, 3).
An instance method belongs to an object. The program creates an object named demo, then calls demo.greet("Ava"). Instance methods can use data stored in their object.
Exercise
What value does add(4, 6) return, and which values are its arguments?
Show answer
It returns 10. The arguments are 4 and 6.