Understanding Methods in Java Programming
Q: What is a method in Java and how do you call one?
- Java
- Junior level question
Explore all the latest Java interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Java interview for FREE!
In Java, a method is a block of code that performs a specific task. A method is designed to be reusable, which means that you can call it from different parts of your program to perform the same task.
Here's the basic syntax for declaring a method in Java:
access_modifier return_type method_name(parameter_list) { // method body return return_value; }
Here's what each part of the method declaration means:
- `access_modifier`: This specifies the level of access to the method. The most common access modifiers are `public`, `private`, and `protected`.
- `return_type`: This specifies the data type of the value returned by the method. If the method doesn't return a value, you can use the `void` keyword.
- `method_name`: This is the name of the method, which you use to call it from other parts of your program.
- `parameter_list`: This is a list of parameters that are passed to the method when it's called. Each parameter is specified with a data type and a variable name.
- `method body`: This is the code that's executed when the method is called.
- `return_value`: This is the value returned by the method. If the method doesn't return a value, you can omit this part.
To call a method in Java, you use the following syntax:
return_value = method_name(argument_list);
Here's what each part of the method call means:
- `return_value`: This is the value returned by the method, which you can assign to a variable or use in an expression.
- `method_name`: This is the name of the method that you want to call.
- `argument_list`: This is a list of values that are passed to the method as arguments. Each argument must match the data type of the corresponding parameter in the method declaration.
Here's an example of a method in Java that adds two numbers and returns the result:
public int addNumbers(int num1, int num2) { int sum = num1 + num2; return sum; }
In this example, the method name is `addNumbers`, the return type is `int`, and there are two parameters of type `int`. The method body adds the two numbers and returns the result.
To call this method, you can use the following code:
int result = addNumbers(5, 10); System.out.println(result); // output: 15
In this example, the method is called with two arguments (`5` and `10`), and the result is assigned to a variable named `result`. Finally, the result is printed to the console.
In summary, a method in Java is a block of code that performs a specific task and is designed to be reusable. To call a method, you use the method name followed by a list of arguments in parentheses. The method can return a value, which you can assign to a variable or use in an expression.


