Java Method – Declaring and Calling Method with Example

Imagine you have to wake up every day and perform a specific task. This task can be anything, be it brushing your teeth to playing with your dog. Consider you have to wake up every day and give milk to the street dogs. They absolutely love you and you love them too! However, one day you fall sick and are unable to get out of bed. You ask your mom/dad to give milk to the poor puppies outside your house. You simply tell them where you have kept the bowl and milk and they do the same thing as you do every day!

Your mom/dad now are examples of methods. You pass them the information in place of method arguments and they perform the function assigned to them by you. Java methods work exactly like this. Let us dive in!

Methods Declaration in Java

Java Methods

  • Methods are the lines of code that performs a specific function in a program.
  • Methods can either return a value or not return anything.
  • The methods which do not return anything are of type void.
  • The main advantage of methods in a program is code reusability.

Stay updated with latest technology trends
Join DataFlair on Telegram!!

Need for Methods in Java

Applications around the world get built for solving problems. However, when building an application there is absolutely no need for programming each and every part of it. This is where methods come into play. If you need to implement a particular function in your application which is already programmed by someone else, you can directly implement that method in your application without worrying about that function at all.

For example, if you are writing a function that prints all the prime numbers from 1 to 100 you can simply use a prime method and print only those numbers which yield true boolean value when passed through this method.

Methods simplify programming and segments blocks of specific code which makes it easy to debug. It also enhances code readability and reusability.

Syntax breakdown of Java Method

The syntax of a method declaration consists of the following points:

1. Modifier

We learned about access modifiers in previous articles. We can specify the access of the method by modifiers. There are primarily 4 types of modifiers in Java:

a. public- this makes the method accessible to all classes in your application
b. private- this renders the method accessible only within the class and its subclasses.
c. protected- it makes the method accessible within the class.
d. default- this renders the method accessible within the same class and package.

2. return type

This is the return type of the method. It can be void if the method does not return anything or it is the datatype of the value that the method returns.

3. method name

A method name should typically represent what its function is. It should be a verb in the lowercase. However, if the verb is more than one word, the camel case is used to write the name of the method.
Generally, to add more definition, an adjective or a noun exceeds the name of the method.
Method names are unique, however, to implement polymorphism method names can be the same at times.

4. parameter list

This list encloses all the parameters that are a part of the method. First brackets enclose them(). However, if there are no parameters, you must use empty parentheses.

5. Exception list

This list includes the exceptions that you can expect that the method can throw. There can be multiple exceptions.

6. Method body

Curly braces{} enclose this body. Upon invoking the method, the statements inside these braces execute and return a value, or no value, if it is a void function.

7. Method Signature

The method name and the parameter list together is the method signature. This does not include the return type and the exceptions.

Example Syntax of a method signature:

public static add(int x,int y)

Java Static and Non-Static Methods

Static methods do not need objects to execute. However, there is a need for objects for accessing non-static methods.

Java program to illustrate the use of static keyword in Java:

package com.dataflair.javamethod;
public class BasicMethod {
  static void staticmethod() {
    System.out.println("Hey! I am inside a static method. ");

  }
  public void nonstaticmethod() {
    System.out.println("Hey! I am inside a non-static method. I need an object to execute myself! ");
  }
  public static void main(String[] args) {
    staticmethod();
    BasicMethod ob = new BasicMethod();
    ob.nonstaticmethod();
  }

}

Output

Hey! I am inside a static method.
Hey! I am inside a non-static method. I need an object to execute myself!

The object ob accesses the method named nonstaticmethod(). However, if you try to access the non-static method without an object you will end up with an error like this.

error: non-static method nonstaticmethod() cannot be referenced from a static context
nonstaticmethod();

The static context as mentioned in the error is actually the main function. (Note that the main function is static).

The basic syntax of a method is 

< access modifier > <
return type > <method name > ( < parameter list > ) < exceptions > {
  //method body code
}

Calling Method in Java

Method calling in Java implements a stack to maintain the order of execution. The control transfers back to the code that invoked it under the following conditions

a. It executes all the code in the method.
b. it reaches a return statement within the code
c. It encounters an exception

Java program to illustrate the uses of methods in Java:

package com.dataflair.javamethod;
public class BasicMethod {
  public static void getminimum(int a, int b) {
    if (a < b) System.out.println(a + " is the minimum of the two.");
    else if (b < a) System.out.println(b + " is the minimum of the two.");
    else System.out.println("both the numbers are equal");
  }
  public static void main(String[] args) {
    getminimum(5, 6);
  }

}

Output

5 is the minimum of the two.

This program illustrates the use of a method to find out the minimum of the two arguments.

Java Method stack

Method calls in Java use a stack to monitor the method calls in a program. The method call from anywhere in the program creates a stack frame in the stack area. The local variables get the values from the parameters in this stack frame. After the completion of the program, its particular stack frame is deleted. The stack pointer points to each method execution. However, whenever a new method is called the current method execution stops and the stack pointer points to the new method until it finishes execution.

Java program to illustrate the method stack:

package com.dataflair.javamethod;
public class MethodStack {
  static void m1() {
    System.out.println("I am inside the m1 method and going to call the m2 method. ");
    m2();
    System.out.println("The control has returned to the m1 method. ");

  }
  static void m2() {
    System.out.println("I am inside the m2 method and going to call the m3 method");
    m3();
    System.out.println("The control has returned to m2");

  }
  static void m3() {
    System.out.println("I am inside the m3 method.");
  }
  public static void main(String[] args) {
    m1();

  }

}

Output

I am inside the m1 method and going to call the m2 method.
I am inside the m2 method and going to call the m3 method
I am inside the m3 method.
The control has returned to m2
The control has returned to the m1 method.

Passing Methods by Value in Java

If you have experience of programming languages you will be knowing that arguments to a method get passed in two ways, namely, Pass by value and Pass by the method. Since Java does not have the concept of pointers, it is safe to say that Java is a strictly pass by value language.
Passing the arguments by value should follow the same order as mentioned in the method definition.

Java program to illustrate the use of pass by value:

package com.dataflair.javamethod;
public class PassByValueMethod {

  static void add(int num1, int num2) {
    System.out.println("The sum of the two numbers " + anum1 + " and " + num2 + " is " + (num1 + num2));
  }
  public static void main(String[] args) {
    add(5, 9);

  }

}

Output

The sum of the two numbers 5 and 9 is 14

Java Method overloading

Overloaded methods are those methods that have the same name but they differ in the type of arguments they have. These methods make the program readable. This enables the programmer to name several methods having the same names which leads to less confusion. However if each method needs to have a different definition then, only the arguments get changed and not the method name itself. You can easily define another method with the same name but with different arguments.

Java program to illustrate the concept of Method Overloading:

package com.dataflair.javamethod;
public class OverloadMethod {

  static void add(int num1, int num2) {
    System.out.println("The compiler understood you wanted to add two numbers of type int");
    System.out.println("The sum of the two numbers " + num1 + " and " + num2 + " is " + (num1 + num2));
  }
  static void add(double num1, double num2) {
    System.out.println("The compiler understood you wanted to add two  numbers of type double. ");
    System.out.println("The sum of the two numbers " + num1 + " and " + num2 + " is " + (num1 + num2));
  }
  public static void main(String[] args) {
    add(5, 9);
    add(6.3, 8.2);
  }

}

Output

The compiler understood you wanted to add two numbers of type int
The sum of the two numbers 5 and 9 is 14
The compiler understood you wanted to add two numbers of type double.
The sum of the two numbers 6.3 and 8.2 is 14.5

CommandLine Argument in Java

In programming certain information gets passed to a program whilst running it. These are the command line arguments. They follow the program’s name while it is being executed through Command Line Interface.
These arguments are accessible inside the program because java interprets the arguments as strings.

Java program to illustrate the use of command-line args in Java:

package com.datafalir.javamethod;

public class CommandLineArgs {
  public static void main(String[] args) {
    for (int i = 0; i < args.length; i++) {
      System.out.println("The argument number " + i + " is " + args[i]);
    }
  }

}

Upon executing the program in CLI like this:
javac CommandLineArgs.java
java CommandLineArgs Hey these are arguments!

Output

The argument number 0 is Hey
The argument number 1 is these
The argument number 2 is are
The argument number 3 is arguments!

()

Variable Arguments in Java

It is not always possible to know the number of arguments that a method may need during execution. This is where the variable arguments in Java come into play. Variable arguments are represented by three consecutive dots(…). The syntax is datatype… parameterName

However, there are certain rules to declaring variable arguments in Java:

a. only one var-length parameter should be present in a single definition.
b. this parameter must be the last parameter., i.e, all the regular parameters must precede it.

Java program to illustrate variable datatype in Java:

package com.dataflair.javamethod;
public class VarArgsMethod {

  static void printnum(int...numbers) {
    if (numbers.length == 0) System.out.println("There are no numbers");
    else {
      System.out.println("The numbers are");
      for (int i = 0; i < numbers.length; i++) {
        System.out.println(numbers[i]);
      }
    }
  }

  public static void main(String[] args) {
    printnum(1, 2, 3, 4, 5, 21, 56, 67, 56, 5, 56, 5, 34, 63, 453, 52345);
  }

}

Output

The numbers are
1
2
3
4
5
21
56
67
56
5
56
5
34
63
453
52345

Note that we did not specify any limit of numbers in the arguments of the function.

Java finalize Method

Whenever the garbage collector in Java destroys an object, it calls the finalize method. Just before the object gets killed, the finalize method executes and performs all the functions necessary.

For example, This method can close the file when handling files using Java.

The syntax is:

protected void finalize() {
  //Final functions before the garbage collector collects objects. 
}

The finalize method is of type “protected” to prevent access from outside the class. However, it is difficult to know whether the finalize method has actually worked or not. It is because the Java garbage collector may/ may not collect the object during runtime unless the pressure in the memory is high.

Java program to illustrate the use of finalize method:

package com.dataflair.javamethod;
public class FinalizeMethod {

  public void objcheck() {
    System.out.println("The object is still alive. ");
  }
  protected void finalize() {
    System.out.println("Code to be executed before object collection by JVM ");
  }

  public static void main(String[] args) {
    FinalizeMethod ob = new FinalizeMethod();
    ob.objcheck();
    ob = null;
    System.gc();
  }

}

Output

The object is still alive.
Code to be executed before object collection by JVM

We purposely assigned the object to a null value and called the garbage collector to invoke the finalize method.

Quiz on Java Method

Summary

We learned about methods in this article and how we can use them in our programs. Methods are essential to know in Java because Java code once written becomes reusable. Methods also segment and distribute the code effectively for easy documentation and understanding of the program.

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google | Facebook

6 Responses

  1. natalia says:

    Simply wɑnna input on few gеneral things, The website layout is perfect, articles are fantastic

  2. Mohammed Tasi'u says:

    Hello! I created a window using java, and I want to put color to the background and I don’t know how to do so. Help!

  3. Madhu says:

    Excellent work sir…

  4. Tanisha says:

    this is seriously helpful

  5. mack says:

    Im confused. I don’t see where they actually explained the actual process of how to call a method…

  6. mack says:

    So this is it here right? additionObj.additionFunction the additionObj. is calling the additionFunction method right?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.