Java Methods Explained
In this article, we will introduce you to Java Methods or functions. First of all, we will talk about what is a method, how to call a method in java, and why we use methods. After that, we will analyze the method syntax and some useful abilities.
You can also check this tutorial in the following video:
1. Introduction
A Java method is a block of code that is grouped to perform an operation. When calling a method, you can pass some data(variables or parameters)
and after processing them from the code, there will be some results that we use to continue the rest of the program.
2. Technologies used
The example code in this article was built and run using:
- Java 1.8.231(1.8.x will do fine)
- Eclipse IDE for Enterprise Java Developers- Photon
3. Java Methods Syntax
Every Java function must be in class. Java has its own pre-defined methods such as print() or sqrt() but as a programmer, you can make your own. Below you can see how is the syntax of a method:
Here is the syntax of a Java method:
Modifier ReturnType Name (Parameters)Exception{ //code of the method }
- Modifier: Is the access type of the method. There are 4 modifiers:
- private: These methods can not be accessed by anywhere outside the class in which are declared.
- public: These methods are visible to any class in the program whether these classes are in the same or another package.
- protected: These methods can be accessed only by subclasses in other or the same package.
- default: This modifier is used when no access modifier is present and these methods can be accessed by classes in the same package.
- ReturnType: The type of the value which the method will return.
- Name: In this place, we declare the name of the method.
- Parameter: Is the data that we pass to use them in the method. The type of them and the number can be anything.
- Exception: The exceptions you expect by the method can throw.
- Body: The body of a method is the code that defines what the method does.
3.1 How to call a method in Java
To use a function in java you have to call it. A method can return a value or return nothing so we can say that a method is called by its functionality. The call of a method in java is done when the program invokes a function. For example:
Method_call.java
import java.util.Scanner; public class Method_call { public static int num(int i) { i=i*i ; return i; } public static void main(String args[]) { Scanner myObj = new Scanner(System.in); System.out.println("Give me the a number"); int ap = myObj.nextInt(); int result=num(ap); System.out.println("The result is: "+result); } }
At line 12 we can see how we call a method and store the return value in a new valuable.
3.2 Void method versus return type method
Usually, we use a method to print or return any type of valuable. But how we can understand what method does what. For this reason, we need the word “void”. If a method is a “void method” then we have to print on the console a text or a variable, else, we just need to return a value after the processing of the parameters. For example:
Example_void.java
import java.util.Scanner; public class Example_void { public static void first() { System.out.println("Do you love Java?"); } public static int second(String i) { if(i.equalsIgnoreCase("yes")) { return 1; } else if (i.equalsIgnoreCase("no")) { return 2; } return 0 ; } public static void main(String args[]) { Scanner myObj = new Scanner(System.in); first(); String ap = myObj.nextLine(); int num =second(ap); if(num==1) { System.out.println("You are the best"); }else if(num==2) { System.out.println("No one is perfect"); }else { System.out.println("Maybe your answer doesnt fit to my program"); } } }
At highlighted code, you can see how to declare a void and a non-void method.
3.3 Static methods versus Instance Methods
Static methods are the methods that can be called without creating an object of class unlike to instance methods that require an object of its class before it can be called. But where static methods are useful? You can use static methods when you want your code to be shared across all instances of the same class. An example:
Test.java
public class Test { public void Testone () { System.out.println("This is not a static method"); } public static void Testtwo() { System.out.println("This is a static method"); } }
StaticVsNonStatic.java
public class StaticVsNonStatic { public static void main(String args[]) { Test a=new Test(); a.Testone(); Test.Testtwo(); } }
The output is:
This is not a static method This is a static method
At StaticVsNonStatic.java program we can see how we call the two methods and the difference between them. You can see the non-static method uses the object “a” to call it.
3.4 Methods and exceptions
Sometimes methods can throw some exceptions, as a result, the program will not conclude and sometimes it’s difficult to find or solve a problem by yourself. So to secure your code inside of a method we can use the Exception Handling mechanism to handle the runtime errors and maintain the normal flow of the program. To handle these errors we use the Try-Catch-Finally mechanism. To understand how it works see the below example:
Throw_ex.java
import java.util.Scanner; public class Throw_ex { public static int ex() throws Exception { Scanner myObj = new Scanner(System.in); System.out.println("Give me the a number between 1 and 100"); int ap = myObj.nextInt(); if(ap100) { throw new Exception(); } return ap; } public static void main(String args[]) throws Exception { try { int result = ex(); System.out.println("The result is: "+result); } catch(Exception e) { System.out.println("The exception handled by the caller "); } } }
The output is:
Give me the a number between 1 and 100 0 The exception handled by the caller
As you can see at the method we throw an exception and when we call the method at main we handled it. The reason that we could handle the exception is the try-catch. At first, we call the method inside the “try” and after the exception, the “catch” handle the exception, prints a text and the program now can run normally.
4. Recursive method
Sometimes to solve problems we need to break it into smaller problems until we end up to a problem that we already know the answer. To do this we call some methods known as recursive methods. Recursive methods are methods that call themselves. To understand better these methods we did an example below:
Recursive_method.java
import java.util.Scanner; public class Recursive_method { static int fact( int n ) { if (n != 0) return n * fact(n-1); else return 1; } public static void main(String args[]) { Scanner myObj = new Scanner(System.in); System.out.println("Give me the a number"); int ap = myObj.nextInt(); int result=-1; result = fact(ap); System.out.println(ap + " factorial = " + result); } }
The output is:
Give me the a number 10 10 factorial = 3628800
At this program, we saw how to find a factorial number. At “fact ()” method we call itself to do the calculation until the “n” becomes zero.
5. Passing by value vs passing by reference
5.1 Passing by value
Actual parameter expressions that are passed to a java function are evaluated and value is derived. Then this value is stored in a location and it becomes the formal parameter to the invoked method.
5.2 Passing by reference
The formal parameter is just an alias to the actual parameter. It refers to the actual argument. Any changes done to the formal argument will reflect an actual argument and vice versa.
To understand more about passing by reference and passing by value we will do an example.
Pass.java
public class Pass { String name; public Pass(String name) { this.name = name; } public String toString() { return name; } }
Passing.java
public class Passing { public static void swap(Pass Pass1, Pass Pass2) { Pass temp = new Pass(""); temp = Pass1; Pass1 = Pass2; Pass2 = temp; } public static void main(String args[]) { Pass p1 = new Pass("Cat"); Pass p2 = new Pass("Dog"); System.out.println("Before Swap:- a1:" + p1 + "; a2:" + p2); swap(p1, p2); System.out.println("After Swap:- a1:" + p1 + "; a2:" + p2); } }
The output is :
Before Swap:- a1:Cat; a2:Dog After Swap:- a1:Cat; a2:Dog
At the above program we pass two arguments and swap them inside the invoked method, then check if the actual arguments are swapped. If the actual arguments are affected then the mechanism used is pass by reference otherwise it is pass by value.
6. Method overriding
A method is an overriding method when a subclass has the same method as declared in the parent class. The overriding method is used when we want to provide the specific implementation of a method that is provided by its superclass or for runtime polymorphism. Here is an example:
Animals.java
public class Animals{ public void animal() { System.out.println("Here is a wild animal"); } }
Dog.java
public class Dog extends Animals{ public void animal(){ System.out.println("Here is a dog"); } public static void main(String args[]){ Dog an = new Dog();//creating object an.animal();//calling method } }
The output is:
Here is a dog
Here we create an object Dog. As a result, the method animal become an overriding method and the output is the print from the method of the Dog class
7. Method overloading
Overloading methods are the methods that have the same name but different signatures. With the term “signature” we mean the type of the input parameters or the number of them. The advantage of overloading is that we don’t need to create many methods with different names for the same code because of the different number or type of parameters. Here is an example
Overloading.java
public class Overloading { public static void main(String args[]) { Overloading s = new Overloading(); System.out.println(s.div(100, 50)); System.out.println(s.div(100, 50, 2)); System.out.println(s.div(100.5, 50.5,2.5)); } public int div(int i,int j) { int res=i/j; return res; } public int div(int i,int j,int c) { int res=(i/j)/c; return res; } public double div(double i,double j,double c) { double res=(i/j)/c; return res; } }
The output is:
2 1 0.7960396039603961
At this code, we create 3 methods with the same name but different parameters. As we saw we didn’t have an error.
8. Varargs
Another way to save your time from the same method with different types and numbers of parameters is the varargs. Varargs or Variable Argument allows to your methods to accept zero or multiple arguments. The syntax of the varargs is:
return_type method_name(data_type... variableName){}
Here is an example:
Varargs.java
public class Varargs { public static void main(String args[]){ Vprint(100,"Hello world"); Vprint(100,"Hello world","My name is ","John"); } static void Vprint(int i, String... str){ System.out.println(i); for(String s:str){ System.out.println(s); } } }
The output is:
100 Hello world 100 Hello world My name is John
So as we saw above we print all the strings that we have input because of the varargs.
9. Why we use Java methods
So the most important question is why we use methods??
The answer is that a method is used :
- For reusable code: Why write again and again the same code when you can write it once and call it every time with different parameters or use a method with the overloading mechanism which will save you time? Methods are your savior.
- To simplify your code: With methods or functions in java, you can have an order to your code and prevent accidental errors and confusion.
- To create conceptual units: Create methods to do something that is one action in your mental view of the problem.
- For top-down programming: Methods help you to solve big problems by breaking them into little pieces and solve them easier and faster.
10. Download the Source Code
In this article, we learned how to call a method in java, what is a method and why it is used.
You can download the full source code of this example here: Java Methods Explained
In Methods and Exception, Section 3.4, Line 8 will fail to compile as there is something wrong on that line:
if(ap100) { // … remaining code }
There is no variable as ap100 and the output shows that ap value is 0.
Hence the code should be:
if ((ap100) ) { // ..remaining code }
Several of the code samples fail to obey standard Java code style. Method names should always start with a lower case letter. When learning Java it is important to follow style rules.
Thank you, but you forget about very important term: “method signature”