Before jumping directly onto how to call a method, we shall first know what a method is in JAVA.
The method is a code block that only works when called. You can transfer data, known as parameters, into a method. Methods are used to perform certain actions, and are also known as Functions.
In the Java application, the method is used when called otherwise.The main () method is the first method developed by JVM (Java Virtual Machine) in the Java program. If we want to do it any other way, we have to call it from the main () path.
But why are methods used anyway? The purpose of using methods in the Java program is to write logic for applications. However, how it works on the objective of something it is named after. The method can have one function to create its action, or several tasks to create a complete solution.
Creating a Method in java
The method must be declared in class. Defined by the path, followed by parentheses (). Java also offers predefined methods, such as System.out.println (), however, you can also create your own custom methods.
Basically, a method has six fundamental parts. They are modifiers, method name, return type, parameter list, exception list and body.
Calling a Method in java
To drive a path in Java, type the path path followed by two parentheses () and a semicolon ;
In the following example, Method() is used to print text (action), when it is called.
When a method is called, it returns the value to the calling method. It can also perform a task without returning any value to the calling method.
The method can be called anywhere in the program. Each route has one entry point and one exit.
Example:
public class Main {
static void Method() {
System.out.println(“HELLO EVERYONE!”);
}
public static void main(String[] args) {
myMethod();
}
}
// Outputs “HELLO EVERYONE!”
In java, even before all this creating and calling you must also first know which method is required to be called. And for that you must first need to know the different types of methods that java has.
Generally there are 2 types of methods: Predefined methods and User defined methods.
However, here we have covered 4 types of methods in java : predefined methods, user defined methods, instance method and abstract methods. They are explained below.
Pre-Defined Method
In Java, predefined methods are previously defined in the Java class libraries known as predefined methods. Also known as the standard library method or built-in method. One can apply these methods directly by simply calling them into the program at any time
Java programming language contains predefined classes organised into different predefined packages. In the aforementioned categories, there are pre-defined approaches.
Java has over 160 predefined packages containing over 3000 predefined classes. These classes have thousands of options described earlier. Everything is available to programmers via the Java API.
Some of the predefined methods are:print(), max(), sqrt(), length(), etc.
Example:
package predefinedMethods;
public class MaxValue
{
public static void main(String[] args)
{
int num1 = 20, num2 = 50, maxValue;
maxValue = Math.max(num1,num2);
System.out.println(“Max value: ” +maxValue);
}
}
// Outputs Max value: 50
User-Defined Method
A user-defined function (UDF) is a function provided by a user of a program or location, in which case the general assumption is that the functions are built into the system or location.
User defined Java methods, Java Static and Non-static methods, Java method with return value, and Java method without refund value.
Java Static methods
In Java, the static method is a class approach rather than an instance of class. The method is accessible to all classroom events, but the methods described in the case can only be accessed by that class object.
Static method has two main purposes: utility or helper methods that do not require the state of an object. Since there is no need for flexible access to instance variables, having static modes eliminates the need for the caller to instantiate the object to call the method.
You should always use standing methods,
->The code along the way does not depend on the creation of the model and does not apply any instance variable.
->A portion of the code must be shared by all instance methods.
->The description of the method should not be changed or overridden.
Example:
class Calc {
static int product(int x, int y) {
return x * y;
}
public static void main(String[] args) {
int ans = Calc.product(5, 3);
System.out.println(ans);
}
}
Non-static methods
The method that does not stand in Java does not have a ‘static’ keyword before the name of the method. The non-static method belongs to the class object, and you must create an instance to achieve a non static method.
Non-static method can access static method using as follows:
->It can access any static method without creating a class instance.
->The non-static method can access any static variable without creating a class instance because the static variable is class.
Example :
class Calc {
int product(int x, int y) {
return x * y;
}
public static void main(String[] args) {
Calc calcnew = new Calc();
// create an instance of the class Calc
int ans = calcnew.product(5, 3); // call the non-static method
System.out.println(ans);
}
}
User-defined functions allow programmers to create their own computer-based processes and processes; it is the basic structure of any program and is very important in modelling and re-use of code as the editor can create a user-defined function that performs a specific process and simply calls it whenever needed. Their syntax depends entirely on the programming language or application in which they are created.
Creating user-defined method in java
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+” is even”);
else
System.out.println(num+” is odd”);
}
Calling user-defined method in java
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print(“Enter the number: “);
//reading value from the user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
Instance method
Instance methods are methods that require the object of its class to be created before it can be called. In order to request a model approach, we must construct a Class object in which the method is defined.
Example:
public class InstanceMethodExample
{
public static void main(String [] args)
{
//Creating an object of the class
InstanceMethodExample obj = new InstanceMethodExample();
//invoking instance method
System.out.println(“The sum is: “+obj.add(12, 13));
}
int s;
//user-defined method because we have not used static keyword
public int add(int a, int b)
{
s = a+b;
//returning the sum
return s;
}
}
There are 2 types of instance method in java:
-> Accessor Method
-> Mutator Method
Accessor Method
The method which reads the variable of the instance is known as the access method. We can easily see it because the method is prefixed with the word ‘get’. It is also known as ‘getters’. The value of the private field is returned. It is also used to get the value of private fields.
Example:
public int getId()
{
return Id;
}
Mutator Method
Method that reads the instance variable and also modifies the values. We can easily see it because the method is prefixed with the word ‘set’. Also known as ‘setters’ or ‘modifiers’. It does not return anything but accepts parameters that are of the same data type that depends on the field. It is also used to set the value of a private field.
Example :
public void setRoll(int roll)
{
this.roll = roll;
}
Abstract Method
A method with no implementation is known as an abstract method. A method must always be declared in an abstract class first, or in other words, if a class has an abstract method, it should be declared as abstract as well.
A keyword ‘abstract’ is used to create an abstract method. The basic syntax to declare an abstract class, using a general form is :
abstract type method-name(parameter-list);
Let us discuss some of the features of abstract methods. Below are the features of Abstract Method :
- They do not have a body, they just have method signatures.
- If a class has an abstract method it must be declared abstract only, the vice versa is not true
- Instead of curly braces, (;) semicolon is used at the end of the method.
- If a regular class extends an abstract class,then all the abstract methods must be implemented or declared abstract in the class.
Example:
package MyPackage;
//abstract class
abstract class Animal{
String AnimalName = ” “;
Animal(String name)
{
this.AnimalName = name;
}
// declare non-abstract methods
// it has default implementation
public void BasicInfo(String details)
{
System.out.println(this.AnimalName + ” ” + details);
}
// abstract methods which will be
// implemented by its subclass(es)
abstract public void habitat();
abstract public void respiration();
}
class Terrestrial extends Animal
{
// constructor
Terrestrial(String name)
{
super(name);
}
@Override
public void habitat()
{
System.out.println(“leave on land and”);
}
@Override
public void respiration()
{
System.out.println(“respire through lungs or trachea. “);
}
}
class Aquatic extends Animal
{
// constructor
Aquatic(String name)
{
super(name);
}
@Override
public void habitat()
{
System.out.println(“It leaves in water and”);
}
@Override
public void respiration()
{
System.out.println(“respire through gills or their skin. “);
}
}
class AbstractClassDemo
{
public static void main (String[] args)
{
// creating the Object of Terrestrial class
// and using Animal class reference.
Animal object1 = new Terrestrial(“Humans”);
object1.BasicInfo(“are terrestrial beings, they “);
object1.habitat();
object1.respiration();
System.out.println(” “);
// creating the Objects of circle class
Animal object2 = new Aquatic(“Fishes”);
object2.BasicInfo(“are aqautic beings, they “);
object2.habitat();
object2.respiration();
}
}
Conclusion
This article focuses on the methods in the Java programming language. How to create and call methods in java is covered in this article. This article also shares with you some examples of different types of methods in java for you to understand better.