Home Java How to call a Method in Java

How to call a Method in Java

A method in Java refers to a group of lines that performs a single action or operation. It is commonly used because it allows code to be reused, which implies that you can write once and use it many times. It also allows for easy customization.
Upon calling the given method, it will carry out the specified work as soon as the compiler can read the name.

We’ll show you how to invoke a method in Java in this tutorial. In Java, a method is a series of joint statements to complete a task. On the other hand, parameters are data passed into a method. Functions is the other name used for methods.

Each procedure or method is given a unique name. When such a name appears in a program, the program’s execution is diverted to the method’s body. When the method is complete, execution returns to the program code section from where it was invoked, and the program proceeds to the following line of code. When using the System.out.println() method, for example, the system runs numerous statements in the background that are already saved in the library to display a message on the console.

Calling a Method in Java

public static void main(String[] args){
System.out.println("execute statements");
method1();
method2();
}

public String method1(){
  return "method One."
}

public String method2(){
  return "method Two."
}

Process of execution

What are the benefits of using methods? First, to reuse code, create it once and use it multiple times. A modular approach allows different programmers to work on various concepts that can be combined later to build the whole project. The application of methods will be our first step toward modular programming.

You’ll now learn how to write your methods with or without return values, how to call a method with or without arguments, and how to use method abstraction in program design.

Creating a method

A method is declared within a class. It is defined by the method’s name, preceded by parenthesis (). A method definition comprises both the method’s header and body.

Example:

public class ClassDefinition {
  
  public static void newMethod() {
    // code to be executed
    }
  }

Explanation of the code:

  • The public static: modifier specifies the method’s access type.
  • newMethod(): the method’s name
  • The method is static since it is a member of the ClassDefinition class and not an object of the ClassDefinition class.
  • This method has no return value; hence it’s called void.

Note that the word public before a method name indicates that the method can be called from anywhere, including other classes and even different packages or files, as long as the class is imported. There are three additional terms used instead of public. They are private and protected. If a method is protected, it can only be called by this class and its sub-classes (classes that build on top of it). If a method is private, it can only be called from within the class.

Last but not least, there’s a keyword that isn’t even a word. If you had nothing in the place of public, protected, or private, this would be the case. It is known as the default or package-private setting. It signifies that classes can only call the method from the same package.

How do you invoke a method in Java?

In Java, write the method’s name followed by two parentheses() and a semicolon to invoke the method. Method calling is a straightforward procedure. The order of events is the method being called, taking control from the calling program at the point when the program invokes the technique.

When newMethod() is used in the following example, it prints the given text (the action):

public class ClassDefinition {
  
  static void newMethod() {
    System.out.println("Introduction to using methods in Java!");
}

  public static void main(String[] args) {
      newMethod();
  }
}

Parameters in Java Methods

Information can be given as a parameter to methods. Inside the method, parameters are used as variables. Parameters are supplied inside parentheses after the method name. The choice of the number of parameters to use is up to you; use a comma to separate them.

The method findProduct in the following example takes two integers as arguments. When we call the method, we feed it two numbers that will be multiplied by each other inside the method:

public class PerformComputations {
  
  static int findProduct(int num1, int num2) {
    return num1 * num2;
}
  public static void main(String[] args) {
    int result = findProduct(8, 9);
    System.out.println("The product is: " + result);
}
  
}

When working with multiple parameters, the method call must have the same number of arguments as the parameters and pass the arguments in the same sequence.

public class Employee {
  
String firstName;
String lastName;
int age;

public Employee(){

}

public Employee(String firstName, String lastName){
    this.firstName = firstName;
    this.lastName = lastName;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName () {
    return lastName;
}

public void setLastName (String lastName) {
    this.lastName = lastName;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

}

Now we’ll make an instance of the Employee class and use its constructor to initialize its fields, after which we’ll use its method to update the field value:

public class Main {

public static void main(String[] args) {
    Employee emp = new Employee("Ann", "Thompson");
    System.out.println("Employee's name is : " + emp.getFirstName());

    student.setFirstName("Codec");
    System.out.println("Employee's name is: " + emp.getFirstName());
}

}

Using Arguments on the Command Line

When you execute a program, you may want to feed some information into it. It is performed by invoking main with command-line arguments ( ).

When a program is run, a command-line argument is an information that appears after the program’s name on the command line. It’s simple to retrieve command-line parameters from within a Java program. They’re saved in the String array supplied to the main as strings ( ). Below is an example showing all of the command-line arguments invoked.

public class ArgumentsOnCommandLine {
  
  public static void main(String args[]) {
      for(int j = 0; j<args.length; j++) {
      System.out.println("args[" + j + "]: " + args[j]);
      }
	}
}

Overriding Methods

Overriding is a concept that allows a subclass or child class to implement a method already offered by one of its super-classes or parent classes. When a method in a subclass has the same name, parameters, or signature, and return type or the sub-type as a method in its super-class, the subclass method is said to override the super-class method.

// parent class
public class Employee {
  
//Overridden method
public void earn()
{
    System.out.println("Every employee is entitled to earn");
}

}

// child class

public class HourlyEmployee extends Employee{

//Overriding method
public void earn(){
    System.out.println("Earns per the number of hours worked");
}
public static void main( String args[]) {
    HourlyEmployee emp = new HourlyEmployee();
    emp.earn ();
}
}

If a method is invoked with an object from a parent class, the parent class’s version is used, but if the method is invoked with an object from a subclass, the child class’s version is used. In other words, which version of an overridden method gets preference is determined by the type of the object being referenced to and not the type of the reference variable.

Java Method Overriding Rules

  • The method’s name must be the same as the parent class’s method.
  • The parameter in the method must be the same as in the parent class.
  • There must be a link between IS and A. (inheritance)

Overloading of Methods

Method overloading occurs when a class contains two or more methods with the same name but distinct parameters. It’s not the same as overriding. Overriding a given method means having the same name, number of parameters, type, etc. Consider the following example, which contains a single method for finding the numbers product of various types.

public class PerformComputations {

static int findProduct(int a, int b) {
    return a * b;
}

static double findProduct(double a, double b) {
    return a * b;
}

public static void main(String[] args) {
    int int_product = findProduct(8, 13);
    double double_product = findProduct(31.5, 12.85);

    System.out.println("int product: " + int_product);
    System.out.println("double product : " + double_product);
}

}

If the number and type of parameters are different, many methods with the same name can exist. However, the parameters can still be variable.

Conclusion

A method is a section of code that only executes when invoked. It has parameters that refer to data that can be passed into a method. Methods, often known as functions, carry out specific tasks. What are the benefits of using methods? To reuse code, create it once and use it multiple times.

The method has to be created within a class. That is where the method declaration exists. It is defined by the method’s name, preceded by parenthesis (). However, Java has several pre-defined ways, such as system.out.println(), you can write your own to handle specific tasks, as seen in our examples.

You may also like

Leave a Comment