Java Methods Tutorial

Java Methods Tutorial

by Ioannis Makris
61 views

1.Introduction

In this article, we will learn about Java methods through detailed examples.

2. Why We Use Java Methods?

First of all, why do we need Java methods? The most important reasons are:

  • Code Reusability: We can create a method once and call it every time with different parameters or with method overloading that we will analyse later.
  • Code simplicity: Methods or functions in Java can help us have an order to your code and prevent accidental errors.
  • Conceptual units: We can create methods to do something that is one action in your mental view of the problem.
  • Top-down programming: Methods help us to solve problems by breaking them into little pieces until we find an easier and smaller problem to solve.

3. How to Create a Java Method?

A method is a block of code that only runs when it is called and we can pass data, known as parameters, inside it. Methods are used to perform certain actions, and they are also known as functions. Here we can see how is the syntax of a method:

Modifier ReturnType Name (Parameters)Exception{
   //Body
}

Now let’s analyze the syntax:

  • Modifier: This is the access type of the method. There are 4 modifiers public, protected, private, and default. You can read more about Access Modifiers here. Of course after the access modifiers we can add some keywords that characterize the method such as the static, final, sychronized.
  • ReturnType: The type of the value that the method will returns.
  • Name: The name of the method.
  • Parameters: Parameters are the data that we pass and use in the method. The type of a parameters can by anything, from primitives (int, char, boolean) to objects (String, Arrays, or any custom-made object that you might create). Every method can have more zero, one or more parameters.
  • Exception: The exceptions that we expect the method can throw.
  • Body: The code that defines what the method does.

4. How to Call a Method in Java?

In order to use a method, we need to call it. We can do that by writing the method’s name followed by two parentheses () and a semicolon. In case a method has parameters then inside the parenthesis, we need to declare the data that we pass by separating them by commas. A method can return a value or nothing. Let’s see an example of a method with one parameter (Attention! In this example, we can see some keywords such as static and void which we will analyze later):

public class SimpleMethodExample {
   public static void name (String name) {
        System.out.println("My name is " +name );
    }

    public static void main(String[] args) {
        name("Constantine");
        name("Jim");
        name("George");
    }
}

The output is:

My name is Constantine
My name is Jim
My name is George

5. Void Method and Return Type Method

A Java method has the ability to return or don’t return a result. In order to create a method that does not return a value, we can use the void keyword. In case we want to return a value, we can write the return keyword before the value that we want to return. Here is an example of two methods one void method and a return type method.

public class VoidAndReturnExample {

    public static void firstMethod() {
        System.out.println("This is a void method.\n");
    }
    public static String secondMethod() {
        String str="This is a return type method.";
        return str;
    }

    public static void main(String args[]){
        firstMethod();
       System.out.println(secondMethod());
    }
}

The output is:

This is a void method.

This is a return type method.

6. Static Methods Versus Instance Methods

Static methods give us the ability to not use any instance variables of any object of the class they are defined in. Furthermore, static methods take all the data from parameters and do whatever we want from those parameters, with no reference to variables. On the other hand, the instance method is a method that requires creating an object of its class before it can be called. To call an instance method, we have to create an Object of the class. 

So let’s see a static method example:

 public class StaticMethodEx {

        static int add(int x, int y) {
            return x + y;
        }
        public static void main(String[] args) {

            int result = StaticMethodEx.add(5, 5);
            System.out.println(result);
        }
    
}

The output is:

10

Now let’s see an instance method example:

public class InstanceMethodEx {

    public void method(){
        int var = 10;
        System.out.println(var);
    }

        public static void main (String[] args) {
            InstanceMethodEx ob = new InstanceMethodEx();
            ob.method();
        }
    }

The output is:

10

7. Passing by Value vs Passing by Reference

7.1 Passing by Value

The pass-by-value method copies the values from the actual parameters. Then the called method creates its own copy of argument values and then uses them. Since the work of the copy ends, the original parameter doesn’t have any changes.

Let’s see an example:

public class PassByValueEx {

    int i = 10;

 public void call(int i) {
        i = i+10;
    }

    public static void main(String[] args) {

        PassByValueEx eg = new PassByValueEx();
        System.out.println("Before call: " + eg.i);


        eg.call(30);
        System.out.println("After call: " + eg.i);


    }
}

The output is:

Before call: 10
After call: 10

7.2 Passing by Reference

The pass-by-reference method passes the parameters as a reference of the original variable or in other words, we pass the address of the variable. The called function refers to the original values. So the changes that were made in the called function will be reflected in the original parameter.

Let’s see an example:

public class PassByReferenceEx {
    int i = 10;
    public void call(PassByReferenceEx par) {
        par.i = par.i+20;
    }

    public static void main(String[] args) {

        PassByReferenceEx par = new PassByReferenceEx();
        System.out.println("Before call: " + par.i);


        par.call(par);
        System.out.println("After call: " + par.i);


    }
}

The output is:

Before call: 10
After call: 30

8. Java Methods Overriding

A method is an overriding method when a subclass has the same method as declared in the parent class. The overriding method is used when we want to provide a specific implementation of a method that is provided by its superclass or for runtime polymorphism.

Some overriding method rules are:

  • Both the superclass and the subclass must have the same method name, return type and parameters.
  • We cannot override final and static methods.
  • We should always override abstract methods of the superclass

Let’s create an example. For this example, we will create three classes. The Parent class, the Child class that inherits the Parent class, and the Test class to run our program.

public class Parent {
    public void method(){
        System.out.println("This is the Parent");
    }
}

public class Child extends Parent{

    @Override
    public void method(){
        System.out.println("This is the Child");
    }
}


public class Test {

    public static void main(String args[]){

        Parent ob1 = new Parent();
        ob1.method();

        Parent ob2 = new Child();
        ob2.method();
    }
}

Line 9: As you can see we used the @Override annotation. This annotation informs the compiler that the element is meant to override an element declared in a superclass.

The output is:

This is the Parent
This is the Child

9. Java Methods Overloading

The overloading method allows different methods to have the same name, but different signatures mean that the signature can have a different number of input parameters, types of input parameters, or both of them. The reason that we do overloading is that method overloading increases the readability of the program.

Let’s see an example:

public class MethodOverloadingEx {
    public static void main(String args[]) {
        MethodOverloadingEx example = new MethodOverloadingEx();
        
        System.out.println(example.div(10, 5));

        System.out.println(example.div(10, 5, 4));

        System.out.println(example.div(10.5, 5.5,1.5));

    }
    public int div(int i,int j) {

        int result=i/j;
        return  result;
    }
    public int div(int i,int j,int f) {

        int result=(i/j)/f;
        return  result;
    }
    public double div(double i,double j,double f) {

        double result=(i/j)/f;
        return  result;
    }
}

The output is:

2
0
1.2727272727272727

10. Java Methods and Exceptions

Sometimes methods can throw some exceptions, as a result, the program will not end and sometimes it’s difficult to find and solve a problem. In order to secure our code inside of a method, we can use the Exception Handling mechanism to target the runtime errors and maintain the normal flow of the program. To handle these errors we use the Try-Catch-Finally mechanism.

Let’s see an example:

public class ExceptionsInMethodsEx {

        public static int method() throws Exception {

            Scanner myObj = new Scanner(System.in);
            System.out.println("Give me a number between 1 and 100");

            int var = myObj.nextInt();

            if(var>100 || var<1) {
                throw new Exception();
            }
            return var;
        }

        public static void main(String args[]) throws Exception {
            try {
                int res = method();
                System.out.println("The result is: "+res);
            }
            catch(Exception e) {
                System.out.println("The exception was handled!");
            }
        }
}

The output is:

Give me a number between 1 and 100
102
The exception was handled!

11. Conclusion

To sum up, you should, now, be able to use Java Methods in the most efficient way. You can find the source code of the examples, on our GitHub page.

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

Related Posts