Author
Artem Divertitto
Senior Android Developer at United Tech

Java Methods

Published in the Methods in Java group
members
Variables and constants in Java store values, while methods contain a set of operators that perform certain actions. That is, methods in Java determine the behavior of objects and perform actions on some variables. They can perform actions, as well as produce a certain result.

What are Methods in Java?

Methods define the behavior of objects and are a sequence of commands that allows you to perform some operation in the program. In other programming languages, methods are often referred to as "functions", and rightly so. In fact, a method is a function in the mathematical sense. Usually something is supplied to the input of the method (some variables), these variables are processed by a sequence of commands, and then the method produces a result. Chances are you've already come across methods, at least with public static void main(String[] args). This method usually starts the execution of a Java program.

How to Declare Methods in Java?

All methods in Java are created inside classes. They are declared as follows:
accessSpecifier ReturnType name (parameter list) {
//method body
}
For example:
public int addTwoNumbers (int a, int b){

//method body
return}
Where public is an access specifier, int is a type of a variable that method returns, addTwoNumbers is the method’s name, a and b are method’s parameters. Let's take a look in a little more detail. Access specifier is used to define the access type of the method. they can be as follows:
  • public: access to the method is available from any class.

  • private: access is available within the class where it was defined.

  • protected: access is available only inside the package or other subclasses in another package.

  • default: access is available from the package where it is declared. In this case, the word "default" is not written.

Return Type defines the type this method returns. In the above example, int is the return type. If a method returns nothing, the return type is void:
public void printSomething (String myString) {}
Method name is a unique name of your method. We are going to explain some Java naming rules a bit later in this article. In the methods above the names are addTwoNumbers and printSomething. The parameter list is the list of arguments (data type and variable name) that the method takes. In the first example above, "int a, int b" are parameters, in the second, String myString is an argument. You can also leave this field blank if you don't want to use any parameters in the method.

Method Parameters example

public void printSomething (String myParameter1, int myParameter2) {}
Here are two variables, myParameter1 and myParameter2. They are method parameters. is the set of instructions enclosed in curly braces that the method will execute. If the return type of the method is not void, the return keyword must be present in the method body. return is followed by the argument this method returns. So, to create a method, you need to specify its name along with brackets, and in brackets, if necessary, the variables the method will operate on. Before the method name is an access specifier and a type of the variable that the method returns, or void if the method returns nothing. In curly braces, we write the actual method, a sequence of instructions that most often works with the method's arguments. Here is an example of a method that finds the largest number in an array and returns it.
public int findBiggest(int[] numbers) {
   int max;
   max = numbers[0];
   for (int i = 1; i < numbers.length; i++) {
       if (max < numbers[i]) {
           max = numbers[i];
       }
   }
   return max;
}

How to Name a Method?

There are no strict rules for naming methods, but there are guidelines that you should follow if you plan to develop professionally in Java. Method names are very often verbs, written in mixed case, starting with a lowercase letter but using a capital letter for each subsequent word (camelCase). Here are some examples:
int addTwoNumbers (int a, int b)
void run()

How to call a Method

To call a method, it is enough to write its name and set the corresponding variables if they were at the declaration. Let's call the findBiggest method in the main method:
public static void main(String[] args) {
  int[] array = new int[] {5, 7, -2, 6, 7, 1};
  int max = findBiggest(array);
   System.out.println("the biggest number in array is: " + max);
  }
The output of this program is:
the biggest number in array is: 7

Different Types of Methods in Java

In Java, everything is made up of objects, and the behavior of objects is defined by methods. Conventionally, we can say that Java has predefined and user-defined methods. Predefined methods are methods that are included in classes that are part of the Java language itself.

Predefined Methods

Predefined or standard library methods are built into Java. Of course, every programmer can use them or even modify them locally for their programs. The Java class library is located in a Java archive file (for example, *jar) with a Java virtual machine (JVM) and a Java runtime environment. These can be, for example, methods of the Math class such as min(), max() or abs(). Or string manipulation methods like concat(). Let’s create a class with a main method and call a couple of standard library methods.
import static java.lang.Math.max;

public class Test {

    public static void main(String[] args) {
       int a = 5;
       int b = 7;
       int max = max(a,b);
       System.out.println(max);
       String str1 = "I am ";
       String str2 = "here ";
       String str3 = str1.concat(str2);
       System.out.println(str3);


   }

}
Note that in order to use the methods of the Math class, it must be imported at the beginning of the program. If this is not done, you can write the class name before the method name separated by a dot:
int max = Math.max(a,b);

User-defined Methods

These methods are created by programmers for the requirements of their projects. Actually, we have already created the user-defined findBiggest() method above. To consolidate, let's create another method that doesn’t return anything and doesn’t have parameters but responds to the entered name and says hello (that is, output to the console).
import java.util.Scanner;

public class Test {

   public void repeater() {
       Scanner scanner = new Scanner(System.in);
       System.out.println("WHat should I repeat after you?...");
       String s =  scanner.nextLine();
       System.out.println(s);
   }
}

Creating Static Methods in Java

Generally, methods in Java are methods of objects. To call a method, you need to create an instance of the class where this method is defined. However, there are also static methods. They differ from regular ones in that they are attached to a class, not an object. An important property of a static method is that it can only access static variables/methods. They are defined using the static keyword. So, in the Math class, all methods for working with variables are static. We can create something similar to the Math class and collect several static methods in it that can be used without creating an instance of the containing class. Let's call it Numbers.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;


public class Numbers {


   public static int findMax(int left, int right) {
       return (left < right) ? right : left;

   }


   public static boolean isNegative(int number) {
       return number < 0;
   }

   public static long power(long number, int deg) {

       if (deg == 0) {
           number = 1;
           return number;
       } else {
           number = power(number, deg - 1) * number;
           return number;
       }
   }

   public static long abs(long number) {
       return number > 0 ? number : -number;
     }


    public static void main(String[] args) {

       int a = 5;
       int b = 7;
       long c = -7;
       long abs = abs(c);
       System.out.println(abs);
       System.out.println(findMax(a,b));

   }

}
The output of the program is here:
7 7
First, a method is called that looks up the absolute value of the number, and then a method that looks for the larger of the two numbers. You don't need to create an instance of the Numbers class to call these methods because both methods are defined as static.

Applying Instance Methods in Java Code

Instance methods or regular methods can be called on the instance of the class in which the method is defined.
public class Cat implements Voice{
   String name;
   String breed;
   int year;


   public void talk() {
       System.out.println("meow meow");
   }
}
To call the talk() method, you need to create an instance of the Cat class:
public class Demo {
   public static void main(String[] args) {
       Cat cat = new Cat ();
       cat.talk();

   }
}
This program output is here:
meow meow
Methods in Java - 2

Abstract Methods in Java

Abstract methods in Java are methods with no implementation. That is, they don’t contain code when it’s declared. They can only be declared in abstract classes and implemented in their non-abstract descendants. Let’s create an abstract class with one abstract method myMethodAdd().
abstract class DemoAbs {
   abstract void myMethodAdd();
}
Now let’s create a Child class of this abstract class, DemoAbs. Here we should necessarily implement myMethodAdd() method.
public class myClass extends DemoAbs {

   void myMethodAdd() {
       System.out.println("hello");
   }

   public static void main(String[] args) {
       DemoAbs demoAbs = new myClass();
       demoAbs.myMethodAdd();
   }
}

Memory allocation for method calls

This is a rather complex topic that requires more careful analysis. Here we are going to mention only the most basic for a superficial acquaintance with the topic. JVM memory consists of heap and stack areas. The heap is an area of memory that stores Java objects. Stack memory is a temporary area of memory that stores primitive variables and references to method objects. The stack memory contains short-lived values that depend on the method. This type of memory is based on the Last In First Out (LIFO) principle. The stack memory creates a new block when we call a method. It contains local primitive values. When we terminate a method, the block created in stack memory becomes free.

Conclusion

In this article, we got acquainted with the basics of creating methods in the Java language, as well as what methods are in Java and how to work with them. We learned that methods determine the behavior of classes. Without methods it would be impossible for objects to interact with each other. To reinforce what you learned, we suggest you watch a video lesson from our Java Course
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet