Java Methods (With Examples)

Java Methods

Well, we have been seeing some methods since we have discussed many concepts like Strings, Arrays, Math, etc.

Here, we have come across many different methods for doing different tasks, for example, we have a length() method in String class, which returns the length of the string, sqrt() method in Math class to calculate the square root of a number or the sort method in Arrays class for sorting the array into ascending order.

Even all the code we have written till now has been inside a method called main, which is the entry point of the program. These are all methods, which help us do different things.

If you are familiar with some other programming language like C, you might have heard about something called a function. A function is just a block of code that does some task.

When a function is written inside a class, it is called a method. So, we can say that a method is a function inside a class. We can also say that a method is a function, which is there for that particular class/object only. For example, if there are two objects like earphones and a water bottle. These are two real-life objects, which have some different functions.

Now, we can play songs using earphones, but the same thing cannot be done with help of a water bottle(the general water bottles). So, playing songs is a method, which is only limited to earphones, and is not available for water bottles.

Well, as said earlier, a function is some block of code that does some task. So, we can create a function for many things, like calculating the sum of two numbers, or swap two numbers, or finding the square of some number, and so on. In short, the function is going to do some useful tasks.

But one question is that why do we need methods? Well, the answer to this is very simple. We write methods so that we do not need to write the same code again in our program.

This improves the readability and reusability of the program, and even if something goes wrong, now your code is distributed into different functions, so it is easier to identify errors in the code.

Just imagine that you are creating software for an ATM machine, wherein there are many things, like checking the balance, pin activation, validating pin, transaction of some particular amount (depending on several things like the balance in the user’s account, and the money in the ATM).

Writing code in such a condition may become quite tedious, especially when things go wrong.

But if we create a method that checks the balance in the customer account. Another method helps users deposit cash, another which helps users withdraw cash from the ATM, so it would be finer. Well, creating methods every time is not mandatory, but it’s convenient.

Till now, we have come across many methods, through which we do something, like calculating the length of a string, calculating the square root of a number, checking if the strings are equal, sorting the array, and so on.

The thing is that these methods are already written and we are just using them by importing the classes in which they are written. However, we can even create our own methods in our own classes.

The methods which are already written are called pre-defined methods, and the ones which we are going to write are called user-defined methods. So, we are now going to deal with the user-defined methods.

How To Create A Method In Java

The question is now that how are we going to write our own methods? What is the syntax? So, let’s head to the syntax now. First of all, We are going to write our own functions, about which, the compiler has no idea. So, we have to tell the compiler everything about the method. We are going to discuss this as we move further.

Well, we have been using the main method in every program that we have written till now. How do we write the main method? Well, it looks something like this –

public static void main(String[] args){
//here is some code.
}

Similar to this, we are going to write our methods. So, we first should understand what this public, static, void is. The main is the name of the method, and what is that thing in the brackets. Let’s understand these all.

First of all, let’s write the above method format in a generalized way –

access_modifier return_type method_name(some parameters here){
// Here is the code inside the method.
}

Well, this access modifier is something that defines the accessibility or scope of that method. There are some access modifiers like public, protected, private, and the default that we are going to talk about ahead. But just the thing to know here is that the access modifier decides where the method is visible or where it can be used.

  • If the access modifier is private, the method is not accessible outside the class. In other words, if the method is declared private, it is only accessible inside the class, in which the method is created.
  • If the access modifier is protected, then the method is accessible in the same package, but outside the package, only those classes can access this method, which is inheriting that class. If you are confused about this, do not worry, because we are going to cover this in detail ahead, when we learn the concepts of object-oriented programming.
  • If the access modifier is public, the method is accessible to all the classes.
  • If we do not mention any access modifier, then it is a default access modifier. If it is so, then this method is accessible within the same package.

The next thing is the return type. Basically, the return type is nothing but the data type of the value that is returned by the method. We can also say that the method has some value after it executes, and the return type defines the value of the method. The return type can be int, char, boolean, String, etc. If the method returns nothing, the return type is void.

The thing is that if you are saying that this method returns a String, it should return a String only. It cannot even return void. On the other hand, if you write return void, and make the method return an int or string or some other data, again there are going to be errors.

Next comes the method name. Well, this is just the name like any other name, like we are naming variables. Basically, the method name is used when we call the method. It is good if the name is in context to what the method is doing.

Like if we are creating a method to perform the addition of two numbers, we can name the method as addition simply.

Inside the brackets after the method name, we can define some parameters that the method requires to do the tasks(if it requires). It is like, we are giving some data to the method so that the method can do its work. From the above example, the addition method may require two numbers for addition, so it may require two parameters as numbers, which we are required to define here.

These parameters will be used with the same name inside the method. Basically, we can say that we are creating some variables for use inside the method, and the variables are going to have values once the method is called.

Between the curly braces, comes the code that we want to write into the method. This is basically the set of instructions you might want to perform when the method is called.

Again, just writing the method is not sufficient. You also need to call the method whenever you want to use the functionality of the method.

For example, if you have a method with you, which adds two numbers, for using this method, you need to call this method every time you need the addition of two numbers. It is not like you have written the method, and it’s done.

Even in the pre-defined methods, we need to call the methods in order to get the things done.

Please note that for right now, we will be making the methods static, so that we do not need objects to call the methods. We are going to study the static keyword ahead, but here, we are using it, so let’s discuss this a little bit.

Basically, when a method is made static, it becomes a method that belongs to a class, rather than to the object. Basically, we have come across the static as well as non-static methods before.

For example, the method like toLowerCase from the String class, is a non-static method, since it is called using some object of the String class. Whereas, the method like sort from the Arrays class is a static method since we can directly call the method just by using the class name.

Just the case is that they are pre-defined methods, and we are going to create our own methods, both static and non-static ahead.

So, we are now all set to have an example that demonstrates to us the working of methods, and also we will be writing our first method here. This method just says Hello. Have a look at the program-

public class Main {
static void sayHello(){
System.out.println(“Hello”);
}
public static void main(String[] args) {
sayHello(); // this is where we are calling the method…
System.out.println(“This executes after the sayHello!”);
}
}

In the above program, we have created our own method, with the name sayHello. Notice that we have not given any access modifier, so java gives a default modifier and makes it available within the same package.

The method has been declared as static, as mentioned earlier. The return type of this method is void, which means that this method returns nothing.

Also notice that we are writing the methods outside the main method. So, this is like we are writing the method first, and then, inside the main method, for example, we are calling this method. Notice how are we giving the method call.

Well, always remember that the main method is the entry point of the program, which means that the main method is first to execute. Inside the main method, we are giving a call to say hello.

This will call the sayHello method, and it will run. It will do what it is meant to do, and then the control will be back to the main method in this case(or from wherever the method was invoked), and the remaining code in the main method will be executed(if any).

Have a look at the output, and we get to see that at first, the method is executed, and then after the method has finished, we are also able to see the output from the println after the method call in the main. So this defines that after the method
the call has finished, the control is back at the main, and executes the remaining code.

Well, instead of printing inside the sayHello method, we can also return whatever value it is into the main(or wherever the method is being called), and then do something with that value inside the main method. Have a look at the below program which is a demonstration of the same thing –

public class Main {
static String sayHello(){
return “Hello”;
}
public static void main(String[] args) {
String returnedValue = sayHello();
System.out.println(“Message from the sayHello method: “+ returnedValue);
System.out.println(“This executes after the sayHello!”);
}
}

Well, in the above method, the method sayHello is meant to return a String. Notice the return keyword, which we are using to return some value from the method. In the earlier program, we did not use this keyword because that method returned nothing(though we can use it).

But here, when we call the method, the method executes and returns a String, which is stored into the variable returned value, which is again of String type(if your method is returning a string, you would store it into a string variable right?).

Well, we are getting this value returned from the method sayHello so that we can use it further into the main method(or wherever we have returned that value). You would want to do this at times.

For example, if you have a method that performs the addition of two numbers, and returns the addition. You can store the addition if you want to use it later on.

Also notice that we are not passing any arguments to this method(arguments are nothing but the data which is provided to the method). There is a difference between the terms parameters and arguments. The arguments are the actual passed values to the method, and the parameters are the names we use in the function definition. When we pass arguments, the parameters are initialized with the passed values (arguments).

Since we have started talking about the parameters and arguments, let’s now consider a method that accepts the name of the user, and says Hello followed by whatever name is given by the user. Have a look at the program –

import java.util.Scanner;
public class Main {
static String sayHello(String name){
return “Hello “+ name; // here, we are concatenating the strings and returning the resulting string
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print(“Please enter your name: “);
String username = scanner.nextLine();
String returnedValue = sayHello(username);
System.out.println(“The method says: “+ returnedValue);
System.out.println(“This executes after the sayHello!”);
}
}

You can try executing the above code and observe the output.

The program asks for the user input, and then it says Hello followed by whatever string from the user input (for example, if we are giving GyaniPandit as the user input, the string returned would be Hello GyaniPandit).

Well, in the above method, we are passing only one argument.

We can pass multiple arguments, provided that we have declared those parameters earlier while we defined the method.

In the given program, we are performing an addition operation on the two numbers given by the user, which are passed to the method for the addition. The method returns the addition result.

After this, we print the result in the main method. Have a look at the following program –

import java.util.Scanner;
public class Main {
static int addNumbers(int num1, int num2){
return num1+num2;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print(“Please enter the first number: “);
int num1 = scanner.nextInt();
System.out.print(“Please enter the second number: “);
int num2 = scanner.nextInt();
int result = addNumbers(num1, num2);
System.out.println(num1 +” + ” + num2+” = ” + result );
}
}

Well, this time, we were able to pass more than one argument to the method. Make sure that you have defined that variables already. It can be a case that method is not asking for anything, and you are providing some data to it, or the method requires some data, but we are not providing it anything.

Also, the arguments can be of different types, like one may be a string, while another is an integer. If you are wondering why are the variable names same in the method definition, and the variables that are passed as arguments to the method, well, is it compulsory? Not at all.

You can also change the names of the variables in either method to avoid confusion. In fact, there is no confusion, since the scope of the variables is different. The scope of variables defines where the variables are accessible. If you are creating some variable inside the main method and trying to directly access it into another method, it would result in an error.

Later on, we are going to write some programs using methods, through which, we can get a more clear idea about the concept.

One more thing is that when we pass the arguments, it is always passed by value. If you are familiar with some programming language like C, you might be familiar with something called call by reference, but this is not there in java. Also, let’s try a tricky program now. You have to observe the output of the code. Have a look –

public class Main {
static void increment(int number){
number++;
System.out.println(“Value was incremented to “+ number);
}
public static void main(String[] args) {
int number = 10;
increment(number);
System.out.println(“Value after incrementation: “+ number);
}
}

Well, if you observe the output of the above program, you will find that the value of the number after incrementation has not changed to 11 actually, but it’s still 10. But why is it so? We had passed the number and done the increment.

We have also verified that in the method itself, but it was not reflected in the main method. This is because when we are passing the value to the method, a separate copy of the value is being passed, and when we increment the value, the copy value is being incremented, instead of the one we want.

So, when the control is back to the main method, the value at the number variable is as it was earlier.

So, this is also important to understand that when the arguments are passed, they are passed as value, and not by reference.