Java is an object-oriented language and hence requires its methods to be defined in a class. Once a method is defined in a class, it can be called in the main or other methods. There are additionally some built-in methods defined in Java libraries. Call any built-in or self-defined methods utilizing the syntax described in this article.
In this article, we will help you understand how to call a method in Java.
What is a Method?
In Java, a method is like a block of code that performs a particular function and runs only when it is explicitly called. Methods are further commonly known as functions. Each method has its own name. One can pass data into a method using parameters. Moreover, a method has a return type defining the type of data it returns.
According to the convention, the method’s name must be written in lowerCamelCase, where the first letter will always be small. Further, a method needs to have a proper name, specially a verb referring to what it does for example, printContactList(), add(), updateInfo() etc. Every time a program gets a method call, the program execution branches out to the method’s body.
The body’s code runs, and the method returns to the previous code from which it was called and followed by the next line. A method will return to the code that invoked it at the time when:
- It finished all the code in the method and reached its end.
- It throws an exception.
- It reaches a return statement.
Why are Methods used?
Methods are utilized as they allow code to be reused without rewriting it repeatedly. Methods are timesavers and help you keep the code in an organized and readable manner. It makes the code more understandable to multiple coders. It also helps in modularizing the program.
Just in case methods are not used, the program can become extremely lengthy and difficult to test, debug or maintain the code.
Actually, modular fashion allows many programmers to work independently on separate concepts, which can be collected later to create the entire project. The utilization of methods will be our first step in the direction of modular programming.
How to call a method in Java
This section includes everything you want to know about calling a method in java. Opting for instructor-led Java certified training course offered by QuantoKnack can also help you learn everything about Java in the most efficient manner.
Understanding what a method is.
A method is like a series of statements that create a particular function. Once a method is defined, it can be called at different parts of the code to execute the function. This is a useful way to reuse the same code repeatedly. The below-listed is an example of a simple method.
public static void methodName() {
System.out.println(“This is a method”);
}
Declare the class access for the method.
When you define a method in Java, you will have to declare what classes can access that method.
In the above-listed example, the access is defined as “Public.” There are basically three access modifiers you can declare a method:
- Public: Defining the access modifier as “public” before the method name enables the method to be called from any part of your code.
- Protected: The “protected” access modifier only permits the method to be called within its class and subclasses.
- Private: Once a method is declared as private, then the method can only be called inside the class. Only those classes placed in the same package can call the method. This is known as the default or package-private.
Public class MyClass {
Static void myMethod () {
// code to be executed
}
}
Declare the class to which the method belongs.
In our above example, the second keyword, “static,” means that the method belongs to the class and not an instance of the class (object). Static methods should be called utilizing the class name: “ExampleClass.methodExample()”.
If the keyword “static” was not utilized, then the method can be invoked only through an object. For example, if the class was named “ExampleObject” and it had a constructor for making objects, then we can try making another object such as “ExampleObject obj = new ExampleObject();,” and call the method using the below: “obj.methodExample();”.
Package com.test.testing;
Class ExampleClass{
Static int j = 0;
Static void methodExample() {
J++;
System.out.printIn(“The value of static variable/object j is ” + j);
}
}
Class TestStatic{
Public static void main(String[] args) {
ExampleClass.methodExample();
}
}
How to declare the return value
The return value is the name of the value returned by the method. In the above example, the word “void” simply means that the method does not return anything.
If you like a method to return some value, then only replace the word “void<” with the object’s data type. Primitive types consist of int, double, float, and many more. Then you need to add “return” + an object of that type nearly at the end of the method’s code.
When you call a method that returns something, you can use what it returns. For instance, if a method called “someMethod()” returns an integer, then you can use an integer to what it returns using the code:
“int a = someMethod();”
Public class MyClass {
Static void myMethod() {
//code to be executed
}
}
Declare the method name
Once you’ve declared the classes that can access that method, the return value, and the class it belongs to, you should give the method a name so that it can be called. Just type the method name followed by an open and closed parenthesis to give the method a name.
The above examples include, “methodName()” and “someMethod()”. Then, you need to input all the method statements inside opened and closed curly brackets “{}.”
Public class className {
Public static void methodName() {
System.out.printIn (“This is a metho”);
}
Public static void main(String[] args) {
methodName();
}
}
How to Call the method
In order to call a method, you need to type the method name accompanied by open and closed parentheses on the line you want to implement the method. Ensure you just call a method within a class that has access to it. Below is an example of a method that is declared and then called within the class:
public class className {
public static void methodName(){
System.out.println(“This is a method”);
}
public static void main(String[] args) {
methodName();
}
}
Add a parameter to a method (if required).
Many methods need a parameter such as an integer (a number) or a reference type such as the name of an object. A method that demands an integer parameter of an integer will look like “someMethod(int a)” or similar.
A method that uses a reference type would look like “someMethod(Object obj)” or similar. If a method requires a parameter, you simply type the parameter between the open and closed parenthesis after the method name.
Public Class MyClass {
Static void myMethod(String fname) {
System.out.printIn (fname + “Good Student”);
}
Calling a method with a parameter
When calling a method that demands a parameter, you will need to add the parameter in the parentheses just after the method name. For instance: “someMethod(n)” or “someMethod(5)” where “n” is an integer.
Just in case the method requires a reference object, simply enter the object’s name in the open and closed parenthesis. For example, “someMethod(4, thing)”.
Public Class MyClass {
Static void myMethod(String fname) {
System.out.printIn (fname + “Good Student”);
}
Public static void main(String[] args) {
myMethod(“Jane”);
myMethod(“Amy”);
myMethod(“Sanjay”);
}
}
How to Add multiple parameters to a method
Methods can additionally have multiple parameters, ideally separated by commas. In the below-listed example, a method is created to add two integers together and return the sum as the return method.
At the time when the method is called, the two integers are given as parameters that will be added together. When the program is running, you will get an output that states, “The sum of A & B is 50”.:
public class myClass {
public static void sum(int a, int b){
int C = a + b;
system.out.println(“The sum of A & B is “+ C);
}
public static void main(String[] args) {
sum(20, 30);
}
}
Conclusion
By now, you must be familiar with methods in Java and how to call them. You can try calling different user-defined, static, or abstract methods with different parameters and return types as a challenge. It will further help you polish your knowledge of methods in Java.
To gain more confidence in your learning, you can register for QuantoKnack’s Java online training course.