Java methods are reusable blocks of code that perform a specific task. A method is a collection of statements that are grouped together to perform an operation. When a method is called, the code inside it is executed. Methods are used to avoid code repetition, and to make the code more organized and easier to maintain. In Java, a method is defined with a return type, a name, and a set of parameters. The return type indicates the type of data that the method returns if any. The name is used to call the method. The parameters are optional, and they represent the input that the method takes.
To call a method, you simply use its name, followed by the argument list enclosed in parentheses. The argument list consists of the values that you want to pass to the method. When the method is called, it executes its statements and optionally returns a value. Java provides many built-in methods, such as print and println for printing output, and Math methods for performing mathematical operations. Additionally, you can define your own methods to perform specific tasks in your program.
What Is Function?
In simple words, a function is a block of codes that performs a specific task. It can be called and reused multiple times. We will discuss function calls later. You only need to remember now that once a programmer defines a function(code to perform a specific task), they can call it whenever they need it, simply using its name. Additionally, in order to work properly or at all, some functions may require some inputs(we call them arguments) or parameters as is called in mathematics, which must be given to the function each time we call them. If it helps to understand, you may think of functions as little machines that perform some chores, where the parameters are inputs to the machine. Some functions may return some value after the completion of their assigned tasks.
A function is a block of code that only runs when it is called. A function is a type of procedure or routine. As mentioned above, how to call a function will be discussed later in this tutorial.
Functions are used to perform specific actions. Sometimes it is required to pass some data to a function so that it can complete its task. You can pass data into a function. The data we pass into a function is known as parameters. We use functions in programming to reuse code. We write the code once and use it many times.
In a nutshell: a function is a code tool that is used to organize source code. If a program does the same thing two or more times, rather than write the same lines of source code two or more times, you write it in a function and call the function whenever it is needed. Using a function, in this case, has the benefits of decreasing the incidence of bugs, and increasing maintainability.
So far, the programs you have seen included only one function(in Java known as method):main(). Most real-world programs, however, will contain many functions(methods).
Why Should We Create And Use Function?
If we want to write a program, we have to write codes. We also need to organize the code. The organization of codes is essential for a lot of reasons – Bug finding, bug fixing, error handling, making code more readable, using the same code again and again to perform the same type of tasks rather than writing the same piece of code from scratch again and again. We can organize our codes in a number of ways. The function is one of them.
To realize the importance of function let us consider the English language. In the English language, we have punctuation marks and paragraphs. They help us to break what we want to say in smaller chunks, so that people can understand it better.
Like many other natural language elements we have also brought this idea in programming. First, it started with execution lines. Then followed the loops and if-else.
But as this field progressed rapidly the size of the program became larger and larger so did the size of the source code. Naturally, it became very difficult to understand a big chunk of code. So a lot of effort was put into devising a new way to break the big monolithic code into smaller readable code.
One of the ways to achieve this is to create and use functions. It became a better way to modularize. The function is basically a way of grouping execution lines of codes in one chunk and naming it. We name a group of code uniquely so that we can call that group later by name, like calling someone. We don’t know what we would be calling each other if our forefathers (or foremothers) wouldn’t devise names to call us. Sure they were the first inventors of names for objects.
Creating a function forces you to give it a name, which documents its purpose better than a comment next to those few lines of code. Creating a function makes the code where you use easier to read because instead of hundreds of lines of implementations, you see a string of carefully named operations.
What Is The Method?
The idea of function is called by different names in different programming languages. In Java, we call them methods. Why? There is a strong reason for this. But it is out of the scope of this tutorial.
From now on we will call functions methods. In Java, every instruction belongs to a method. Consider the programs we have written so far. Each and every instruction belongs to the main() method. Look at the following HelloWorld program. It has one method – the main() method. Our only instruction in this method is to print “Hello World” to the console. This is also the only task our HelloWorld program has to perform.
public class HelloWorld{
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Look again at the above program. In this program, we printed “Hello World” to the console using a built-in method in Java – println(). If we dissect the whole statement:
System is a final class from the java.lang package. out is a class variable of type PrintStream declared in the System class. println is a method of the PrintStream class
There are many built-in methods declared in java inside the built-in classes of Java. Apart from them, we can also write our own methods inside our own classes.
We will discuss the class, package, and instance variable in the next tutorial.
What Is Method Definition?
A method definition is divided into two sections: the method declaration and the method body.
As shown in the figure below, the method declaration defines all of the method’s attributes, including access level, return type, name, and arguments. Following is the main() method declaration of our HelloWorld Program mentioned above.
The method body is where everything happens. It contains the method’s implementation instructions. Following is the main() method body of our HelloWorld Program mentioned above. The body of a method is between the curly braces.
How Do You Write A Method In Java?
We will take the HelloWorld Program as a reference here to explain how to write a method in Java. We will dissect the main() method to get a better understanding of methods in Java.
It is fairly easy as well as simple to write a method in Java. As all instructions belong to a method, all methods must belong to a class. When we write a Java Application, there may be hundreds of methods and hundreds of classes. Every method must belong to one or another class. Otherwise, the program will not compile. Between the opening and closing curly braces of a class, a method is defined.
In Java, you start defining a method by declaring-
Access Modifier: First you may declare an access modifier(more on access modifiers will be discussed when discussing OOP later). Declaration of access modifier is not mandatory in Java. If we do not declare any access modifier, Java itself assigns a default access modifier to our method.
We will discuss access modifiers in great detail in a later tutorial. You may totally avoid using the access modifier until we do so. But as we told you before the main() method will always have to declare as it is – otherwise, the JVM will not find it causing our program not to start executing. Remember, our program starts executing from the main() method. And the JVM looks for this method. So the main method will always have to have a public access modifier.
Static: We will skip the static for now as it requires us to understand some concepts that are yet to be discussed. But for now, keep in mind that for every method you define you have to have a static keyword declared in the method declaration. This is true until we discuss classes and fields.
Return type: Next we have to declare the return type of the method. We must declare what type of value this method returns to the caller. If the method does not return any value we must declare void as the return type. It is mandatory in Java to declare a return type of a method. Do not worry. We will discuss it in this tutorial in the next section.
Method Name: Of course, you have to name a method something to call it in the future.
Parameter-list: We must declare the types of inputs as well as their placeholder names, that a method may need, in the enclosed parentheses followed by the method name. This is the parameter list of the method. We can declare as many parameters as we want or may need. If the method does not take or require any input to perform its task, then the parameter list is left empty. In other words, if there are no parameters, you must use empty parentheses ().
Two of the components of a method declaration comprise the method signature—the method's name and the parameter types. When you call a method from anywhere in your program you call the method by its method signature.
Method body: We have to declare the method body. The method body is enclosed between curly braces. The statements that must execute in order to perform our intended task, must be inside the opening and closing curly braces of the method body.
In this main() method we have only one statement but there may be hundreds, even thousands of statements in the method body.
This is enough for now for methods. Please remember that this article is not meant to be referenced. This article is intended solely for one thing – explain some complicated terms in easy words so that you may understand them a little better.
NOTE
In Java it is a must to declare a method within a class. In every program we have written so far if we went back to inspect we would notice that the main() method is defined in a class. To define a method you have to give it a name followed by parentheses ().
Let us write a program to add two numbers. For simplicity, we will write the instructions in the main() method and work our way from there.
public class Add{
public static void main(String[] args) {
int num1=2;
int num2=5;
int result = num1 + num2;
System.out.println(result);
}
}
Output:
7
In this program:
- main() is the name of the method and has no parameters.
- static means that the method belongs to the Add class and not an object of the Add class. We will discuss this when we talk about Class.
- void means this method does not have a return value i.e. it does not return anything. This will become clear when we talk about Calling a Method later in this tutorial.
We are going to create our own method(not the main method) in the following program.
class MethodCreation{
static void myMethod(){//method name
System.out.println("Hello From myMethod()");//instruction to execute
}
}
The return type, name, a pair of parentheses () for no parameters(or the parameter-list in the parentheses when the method takes parameters), and a body between braces, are the only required elements of a method definition.
Naming Convention of Method
According to Java Docs
Despite the fact that a method name can be any legal identifier, code conventions have some restriction on method names. Method names should, by convention, be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, and so on. If a method name has more than one word, the first letter of each of the second and subsequent words should be capitalized. Here are a couple of examples:
- run
- runFast
- getBackground
- getFinalData
- compareTo
- setX
- isEmpty
Typically, a method has a unique name within its class. However, a method might have the same name as other methods due to method overloading. We will discuss it later. Hold tight for now.
How To Call A Method?
In Java, when we want to call a method we call it by its method signature. It was earlier mentioned that every method signature consists of a method name and parameter list.
To call or invoke a method, write the method name followed by two parentheses () and a semicolon to call a method if it does not have any parameters. If it has parameters just pass the parameters in the parentheses. It will become clear to you how to pass parameters in a method within a few minutes.
When myMethod() is called in the following example from the main() method, it prints a text (the action):
class MethodCreation {
public static void main(String[] args) {
myMethod();
}
public static void myMethod() {
System.out.println("Hello From myMethod()");
}
}
Output:
Hello From myMethod()
We can also call a method multiple times.
class MethodCreation {
public static void main(String[] args) {
myMethod();
myMethod();
myMethod();
}
public static void myMethod() {
System.out.println("Hello From myMethod()");
}
}
Output:
Hello From myMethod()
Hello From myMethod()
Hello From myMethod()
When you call a method from a program, the program is paused and the method starts to execute. The method is read in a specific order- First top to bottom, then left to right. Once the method is complete, in other words, all its instructions are executed, the program continues to run from where it had paused. The following program demonstrates this concept:
Public class MethodCallDemo{
public static void main(String[] args) {
System.out.println("Hello from main() method");
myMethod();
System.out.println("Bye From main() method");
}
public static void myMethod(){
System.out.println("Hello from myMethod() method");
System.out.println("Bye From myMethod() method");
}
}
Output:
Hello from main() method
Hello from myMethod() method
Bye From myMethod() method
Bye From main() method
If we consider the life cycle of this MethodDemo program
First, we create a source file named MethodCallDemo.java. Then we write our source code in a public class called MethodCallDemo. We have two methods in this class: the main() method and myMethod(). main() method has three statements to execute. mymethod() has two statements to execute.
After writing the source code we compile it and generate a .class file called MethodCallDemo.class
Action : javac MethodCallDemo
Result : A .class file is generated called MethodCallDemo.class
Then We run the program and four lines are printed in the console.
Action : java MethodCallDemo
Result : Four lines are printed in the console
Line1 : Hello from main() method
Line2 : Hello from myMethod() method
Line3 : Bye From myMethod() method
Line4 : Bye From main() method
If we now try to explain the inner workings of the program then this will be something like this. When we run the program using java then the JVM tries to find the main() method. If the JVM finds the main() it starts executing the statements in the main method. In our main() method of the MethodCallDemo program, the first statement is a print statement that tells the println() method to print “Hello from the main() method” in the console. Notice “Hello from main() method” is the argument to the println() method. The println() prints the arguments as passed in the console, in our case it is: the “Hello from main() method”.
In the next statement in the main() method myMethod() is called. Now the main() method is paused and the controls go to the myMethod. In other words, the myMethod() starts to execute.
We are now in the myMethod(). This method has two statements to execute. First the argument “Hello from myMethod() method” is passed to the println() as an argument and println() this as it is in the console. Next the argument “Bye from myMethod() method” is passed to the println() as an argument println() prints this as it is in the console. Now all the statements in the myMethod() have been executed.
Now the main() method resumes executing right next to where it stopped. The next statement is to print a line using println(). The argument “Bye from the main() method” is passed to the println() as an argument, println() then prints this string as it is in the console. Now all the statements in the main() have been executed. And so the program terminates
Note
If you want to directly call a method in the same class from the main() method then that method must have static declared before the return type.
How To Pass Arguments To A Method
You can send things to a method. You can pass values into your methods just like you would in any other programming language. In this tutorial, we will only tell you how to pass primitive type values.
- PARAMETER → PLACEHOLDER (This means a placeholder belongs to the function naming and be used in the function body).
- ARGUMENT → ACTUAL VALUE (This means an actual value that is passed by the function calling).
Please keep in mind that parameters refer to the list of variables in a method declaration. Arguments are the actual values passed into the method when it is called. When you call a method, the arguments must be of the same type and order as the parameters in the declaration.
Let us mention it again – every method signature consists of a method name and parameter list. When we want to call the method we call it by its method signature. If a method does not take any input, in other words, if we do not have to pass any data to the method, then we call the method by its name followed by two parentheses(). This means an empty parameter list for both method definition and method call.
Now let us discuss the scenario where the method definition has a parameter list. The parameter list may have one or more data types in it. When we call the method we need to pass that type of data to the method. Let us consider a program. In this program we pass two numbers to a method and the job of that method is to add those two numbers and display the result in the console. In this case, we need two methods: main() method from where JVM starts executing the statements. In the main() method we also declare and initialize the two variables. We also call the add(num1,num2) method from the main() method where num1 and num2 are the arguments that need to be passed to the add() method.
You can pass variables into a method, as long as the variable type matches the parameter type.
The add() method declares a variable called the result, calculates the sum of its two arguments, and stores the sum in the result variable. Then it prints the result on the display.
class MethodCallDemo2{
public static void main(String[] args) {
int num1=2;
int num2=5;
add(num1, num2);
}
public static void add(int num1, int num2){
int result = num1 + num2;
System.out.println("Result : " + result);
}
}
Output:
Result : 7
In our add() method declaration it has two parameters: num1 and num2. They are int-type data. When we called it then we passed two int-type data: 2 & 5. These are the arguments. num1 and num2 are placeholders or parameters. 2 & 5 are actual values or arguments.
What Type Of Arguments Can We Pass To A Method?
We can only pass arguments of the type that were defined as parameters in the method signature. So the real question we should ask is what type of data we can use as parameters of a method. The answer to this question is that you can use any data type for a parameter of a method. You can use primitive data types such as doubles, floats, integers, etc. as parameters. You can also use reference data types such as objects and arrays as parameters.
Suppose you have an array of numbers. You want to find the maximum number in that array. You have read and realized the importance of using methods in programming. So you want to do the task of finding the maximum number in that array using a separate method and print the maximum number in the console. How do you do it? You start by defining a method. Method definition has two parts: declaration and method body. We will ignore the method body for now as there are many ways to find the maximum number in an array. We are now only concerned with how the method declaration would look like.
It would look like this
public int maxNumber(int[] arr){
//method body goes here
}
Look carefully here. This method needs an array so that it can find the maximum number in that array. We have to pass an int-type array to the method. This is a solid example of a method that accepts an array as an argument.
Look again at the parameter type in the method declaration. The parameter is of type int. The maxNumber() method only takes an int-type array as its arguments. We can not pass a double-type array to the maxNumber() method. In other words, this array does not accept an argument of double type on any other type of array except for the int type of array. Keep this in mind. That is all for now. You will get to know more after we discuss classes.
Naming Parameters
Parameters are one kind of variable. The naming conventions used for variable names also apply here. When you declare a parameter to a method, you give it a name. This name is used to refer to the passed-in argument within the method body.
When we discussed variables we mentioned that Variables are the names given to computer memory locations where values are stored in a computer program. It is difficult to name variables, but it is necessary. Our code must be as descriptive as possible. Any other developer who may read one of our programs in the future should be able to figure out what our code does. sensible and descriptive variable (and method) names go a long way to serving this purpose.
Our variable names should be descriptive of what they contain while also being concise. This can be difficult to accomplish. You might even be concerned about running out of unique, descriptive, and concise variable names. Don’t worry, all programming languages have what’s known as scope. The term “scope” refers to the fact that not all variables exist everywhere in a program. If they did, a variable you write in file A might accidentally overwrite a variable created by your friend in file B. When you have a scope for variables, you can be more confident that you are not overwriting someone else’s work when you create variables.
How To Get Value From A Method?
Well, like any programming language that is worth its salt, you can get things from a method. Methods can return values. Every method has a return type, but up until now, we’ve given all of our methods a void return type, which means they don’t return anything.
However, we can declare a method that returns a specific type of value to the caller. As an example look at the following code snippet:
int getCount(){
return 23;
}
This method returns an int type value, and the value of that int is 23. If you declare a method to return a value, that value must be of the declared type! Or, a value that is compatible with the declared type. We’ll go over this in greater detail when we discuss polymorphism.
The following ReturnDemo program demonstrates this:
public class ReturnDemo{
public static void main(String[] args) {
int num1=2;//declaring first variable and assiging a value
int num2=5;//declaring second variable and assiging a value
int result;//declaring third variable
result = add(num1, num2);//storing the value returned by add() method in result
System.out.println("Result : " + result);
}
static int add(int num1, int num2){
int result = num1 + num2;
return result;//returning an int type variable result
}
}
What Is Scope?
We carefully avoided discussing the scope in the variables tutorial. Now the time has finally come when we can discuss the scope in detail.
The term “scope” refers to the areas of your program where you can access certain data. Variables in Java are only accessible within the region in which they were created. This is referred to as scope.
Method Scope
Variables declared directly inside a method are available anywhere in the method after the line of code where they were declared.
public class MethodScopeDemo {
public static void main(String[] args) {
// Code here CANNOT use number
// If you want to print the number here
// the program will not compile.
int number = 23;
// Code here can use number
System.out.println(number);
}
}
Remember that a variable defined within a method cannot exit that method. Outside of the method, it is not available to your program. A variable defined inside of another method can only be made available to the code inside a method if it is passed in as an argument to the method.
public void methodOne() {
int x = 2;
}
public void methodTwo() {
int y = x;/*This line will complain and the program will not compile*/
}
Block Scope
A block of code or code block is any code that is enclosed by curly braces.
Variables declared inside code blocks can only be accessed by the code between the curly braces that follow the line where the variable was declared:
public class BlockScopeDemo {
public static void main(String[] args) {
// Code here CANNOT use number
{ // This is a block
// Code here CANNOT use number
int number = 100;
// Code here CAN use number
System.out.println(number);
} // The block ends here
// Code here CANNOT use number
}
}
A block of code can exist independently or as part of an if, while, or for statement. Variables declared in the statement itself are also available within the scope of the block in the case of for statements.
A parameter’s name must be unique within its scope. It must not be the same as another parameter for the same method, nor can it be the name of a local variable within the method.
A parameter’s name can be the same as one of the class’s fields. In this case, the parameter is said to shadow the field. Shadowing fields can make your code difficult to read and is typically reserved for constructors and methods that set a specific field. We will talk about class and constructors in the next tutorial.