In this tutorial, we will learn the concept of Methods in Java detail. We will learn the following concepts related to Java methods:
- Java method types
- Method Syntax
- How to call the method
- Parameters, Arguments, and Return Values
- Access Modifiers
- Memory allocation for Method calls
- Method Overloading
Simple programming examples are also included for clarity.
=> Check Out The Perfect Java Training Guide Here.
Table of Contents:
Java Method Types
Let’s have a look at the following sample Java program:
package com.softwaretestinghelp; public class DemoClass{ public static void main (String[] args){ System.out.println("Hello , this is sample program"); double d = Math.random(); System.out.println("Random Number:"+d); } }
As seen in the sample code, this program just retrieves a random number and prints it, that’s it! If we have a closer look, we have used 2 methods in the main() method as shown below.
- System.out.println()
- Math.random()
We have not defined these methods in the class DemoClass; we are just using the already available methods that are called as Standard library methods.
Java methods can be classified into two different categories:
- Methods provided by Standard Java library
- Methods defined by Users
Methods Provided By Standard Java Library
Java provides many readily available methods in the Java standard library. These libraries are provided by the class library of Java. This library exists in a Java archive file that becomes available along with the Java Runtime Environment (JRE) and Java Virtual Machine(JVM).
To consume these libraries in our Java code, a jar file called stdlib.jar needs to be added to the Java classpath. Some of the standard library methods we commonly use are Math library methods like Math.random(), Math.sqrt(), or String methods like equals () to compare two strings or concat () to join two strings.
Methods Defined By Users
Along with the readymade standard library methods, a developer can create his/her method as well to perform a certain task. These methods are called as User Defined methods. To create our methods, we first need to understand the concepts and rules to create methods.
So, let’s understand the Java method syntax to define our own Java method.
Java Method Syntax
While considering the definition of the term Method, Methods are considered as procedures associated with a class.
In simple terms, the method is a code block having a collection of statements to perform certain actions. This block of code runs when the method is invoked. Data known as parameters can be passed to the method.
Here the basic question could be, what is the purpose of using methods? the answer to this is, to reuse the code i.e. when a code is defined once in a method it can be used many times.
Let’s see the syntax of the method. Before that, let’s see the following sample method.
}public static void sampleMethod(int a,int b) throws ArithmeticException{ System.out.println("Hello, this is sample method");//<- Method body int c = a/b; System.out.println("c:"+c); }
Given below is the syntax of the method:
modifier non-access_modifier returnType methodName (parameters) throws Exception exceptionName{ // method body }
#1) Modifiers: These are the access type. For Example, public, private, etc. Also, we can specify a non-access modifier like ‘static’.
#2) Return type: When the method returns any value, its data type is specified. If the method does not return any value, then the method is specified as ‘void’.
#3) Method name: This is the name of the method which follows conventions somewhat similar to the Java field names.
#4) Parameters: This is a list of input parameter names with data types separated by a comma. This is enclosed by parentheses (). It is an empty parentheses if no parameters are to be specified.
#5) An exception list: This is a comma-separated list of exceptions that can be thrown by the method.
#6) The method body: This is the place where the method code goes. It is enclosed between braces. i.e. {}
With this understanding, let’s have a relook at the sample method to map these with the sample method that we saw:
How To Call A Method
Now, as we have seen the syntax of the method, let’s see how we can use the method.
By Invoking Method On The Class
package com.softwaretestinghelp; public class DemoClass{ public static void sampleMethod(int a,int b) throws ArithmeticException{ System.out.println("Hello, this is sample method"); int c = a/b; System.out.println("c:"+c); } public static void main (String[] args){ DemoClass.sampleMethod(4,2); } }
Here is the program Output:
Hello, this is sample method
c:2
Here, the method is defined as static. Hence, this method can be called without creating an instance of a class. So, it is directly invoked on the class i.e. DemoClass.sampleMethod(4,2)
By Invoking Method On The Class Instance
package com.softwaretestinghelp; public class DemoClass{ public void sampleMethod(int a,int b) throws ArithmeticException{ System.out.println("Hello, this is sample method"); int c = a/b; System.out.println("c:"+c); } public static void main (String[] args){ new DemoClass().sampleMethod(4,2); } }
Here is the program Output :
Hello, this is sample method
c:2
Here, the method is not defined as static. Hence, to call this method, a class instance has been created first and the method is invoked on an instance of a class i.e. new DemoClass().sampleMethod(4,2)
Multiple Method Calls
We can invoke the same method multiple times as seen in the below sample program:
package com.softwaretestinghelp; public class DemoClass{ public static void sampleMethod(int a,int b) throws ArithmeticException{ System.out.println("Hello, this is sample method"); int c = a/b; System.out.println("c:"+c); } public static void main (String[] args){ DemoClass.sampleMethod(4,2); DemoClass.sampleMethod(4,2); DemoClass.sampleMethod(6,2); } }
Here is the program Output :
Hello, this is sample method
c:2
Hello, this is sample method
c:2
Hello, this is sample method
c:3
Parameters And Arguments
Parameters
As seen in the above sample method, while calling the method, we are passing information to the method. This information is called as parameters. For Example, as seen in sampleMethod (int a, int b), a and b are called as parameters. These parameters work as variables inside the method.
package com.softwaretestinghelp; public class DemoClass{ public static void sampleMethod(int a,int b) throws ArithmeticException{ System.out.println("Hello, this is sample method"); int c = a/b; System.out.println("c:"+c); } public static void main (String[] args){ DemoClass. sampleMethod(4,2); } }
In the method syntax, we have seen that parameters are specified inside parentheses i.e.(). As seen in sampleMethod(int a, int b), a and b are the parameters specified inside the parenthesis.
These parameter’s data type has to be specified with the parameter name. For Example, the data type of parameter a is specified as int. This data type can be any valid Java data type as String, double, etc., and also any object type.
We can specify any number of parameters, these parameters have to be separated by comma. For Example, (int a, int b, double c, String d), etc.
Arguments
When we call a method, the actual values are passed for parameters which are called Arguments. For Example, when we are invoking sampleMethod(), we are passing actual values i.e. 4 and 2 to DemoClass.sampleMethod(4,2);
Here, a list of actual values we are passing i.e. Arguments should have an exact match to the Parameter list i.e. a number of parameters and their data type.
For Example,
So, Value 4 gets assigned to parameter a
Value 2 gets assigned to parameter b
Actions on a and b inside sampleMethod() take place accordingly
public static void sampleMethod(int a, int b) throws ArithmeticException{ System.out.println("Hello, this is sample method"); int c = a/b; // int c = 4/2 which gets calculated as 2 System.out.println("c:"+c); // c: 2 }
Return Values
Every method executes Java statements written in the method body to perform intended actions to get the intended result and then the method can also return the result value to the invoking method.
When A Method Returns Any Value
[1] Data type of return value needs to be specified in the method.
[2] return statement needs to be written at the end of the method.
package com.softwaretestinghelp; public class DemoClass{ public static int sampleMethod(int a,int b) throws ArithmeticException{ //[1] int as data type of return value System.out.println("Hello, this is sample method"); int c = a/b; // int c = 4 / 2 gets calculated as 2 System.out.println("c:"+c); // c: 2 return c;//return statement } public static void main (String[] args){ int x = DemoClass.sampleMethod(4,2);//return value is assigned to variable x System.out.println("x:"+x); // x: 2 } }
Here is the program Output :
Hello, this is sample method
c:2
x:2
As we have seen here, there has to be one return statement. However, in some methods, you will find multiple return statements i.e. in the if-else loop, like if-else if loop as seen below.
package com.softwaretestinghelp; public class DemoClass{ public static String getGrade(int percentage ) { if(percentage>=60){ System.out.println("A grade"); return "A grade"; //Return statement }else if(percentage>=40){ System.out.println("B grade"); return "B grade"; //Return statement }else { System.out.println("Not Eligible"); return "Not Eligible"; //Return statement } } public static void main (String[] args){ System.out.println("Hello , this is sample program"); String grade = DemoClass.getGrade(70); System.out.println("Grade:"+grade); } }
When A Method Does Not Return Any Value (Void Method)
When the method does not return any value back to its calling method, then the return data type of the method is specified as void.
package com.softwaretestinghelp; public class DemoClass{ public static void sampleMethod(int a,int b) throws ArithmeticException{ //[1] void as method does not return any value System.out.println("Hello, this is sample method"); int c = a/b; // int c = 4 / 2 which comes as 2 System.out.println("c:"+c); // c: 2 // No return statement } public static void main (String[] args){ DemoClass.sampleMethod(4,2); //No result value is returned from the method } }
Here is the program Output:
Hello, this is sample method
c:2
Access Modifiers
We have already seen a method that can be declared as static where we invoke a method on the class itself like DemoClass.sampleMethod(). Also, when a method is not declared as static, then it is called an instance method i.e. method has to be invoked from an instance of a class, For Example, new DemoClass().sampleMethod().
Also, the method can be declared as private, public, protected, and default similar to a Java field.
Memory Allocation For Method Calls
In Java, memory management is done through Heap and Stacks. Heap is a place where the Java objects are stored. In the case of methods, the method calls are managed by Stacks.
When a method is invoked, the stack frame is created, and arguments are passed, and the method’s returned value is stored. On method execution completion, that allocated stack frame gets deleted.
Method Overloading
In our sample Java program, we saw how a sampleMethod(int a, int b) can be defined and used. So, can we have more than one method with the same name i.e. can we define multiple methods with the name sampleMethod() in the same class DemoClass?
The answer to this is Yes. Consider a scenario, if we want to define a method to add two numbers. But these values could be 2 integer numbers or 2 double numbers. In such a scenario, we have 2 different methods with the same name as addNumbers().
This behavior is called Method Overloading i.e. defining multiple methods in the class with the same name provided these methods have a different number of parameters and/or different types of parameters.
Let’s have a look at the below sample program:
package com.softwaretestinghelp; public class MethodsDemoClass { public static void add(int a, int b) { System.out.println("Hello, this is add method"); int c = a + b; System.out.println("c:" + c); } public static void add(double a, double b) { System.out.println("Hello, this is add method"); double c = a + b; System.out.println("c:" + c); } public static void main(String[] args) { MethodsDemoClass.add(4, 2); MethodsDemoClass.add(4.2, 2.3); } }
Here is the program Output:
Hello, this is add method
c:6
Hello, this is add method
c:6.5
FAQ
Q #1) How do you create a Method in Java?
Answer: User-defined methods are created as per the Java method syntax i.e. method declaration with method body is as follows:
modifier non-access_modifier returnType methodName (parameters) throws Exception exceptionName{ // method body }
For Example:
public static void someCalculation(int x, int y) throws ArithmeticException{ int z = x/y ; }
Q #2) What are the types of Methods in Java?
Answer: There are two types of methods in Java:
- Methods provided by Standard Java library
- Methods defined by Users
Q #3) What is the main Method in Java?
Answer: The main() method is considered as a starting point to an application as this is predefined and configured into JVM. To execute a Java program, JVM looks for the main() method and executes statements inside the main() method.
Here is the syntax of the main() method:
public static void main(String[] args){}
args is an array of String class. Command-line arguments are passed through the args parameter.
Q #4) Is Method and Function the same in Java?
Answer: The concept of Method and a function is the same. As per the OOPS programming concept, it is a procedure that is a reusable block of code that can be called from anywhere in the program. In Java, the term used for this reusable code is Method.
Q #5) Why are methods used in Java?
Answer: Methods are written in the Java class to perform some specific task. Usually, methods are written for some tasks that may be required to be performed multiple times in the Java application. Methods save time and effort to write the same block of code every time when it is required to perform the same task.
For Example,
public int add(int a, int b){ return a+b; }
Thus, the main purpose of using a method is its reusability to save time, effort, and improve the readability and maintainability of the Java program.
Q #6) What is print () in Java?
Answer: Java print() method is used to print text on the console and keep the cursor at the end of the text. i.e. when the next print() method is invoked, text printing starts from the end of this location.
Any of the primitive Java data type or object can be passed as an argument which gets displayed on the console as text.
For Example, void print(String s): method prints a string.
void print(int s): method prints integer value
Java also has the println() method which functions the same as the print() method except for its cursor position. Every time when the println() method is called, it prints the text and the cursor is moved to the start of the next line.
Conclusion
In this tutorial, we explored the concept of Java Methods in detail. We saw the syntax of the method along with the concept of parameters-arguments, return type, access modifiers, type of methods, and method overloading.
=> Visit Here For The Exclusive Java Training Tutorial Series.