Java Methods Explained (with Code)

Java Methods Explained (with Code)

4 mins read1.2K Views Comment
clickHere
Updated on Oct 12, 2023 17:32 IST

The below java tutorial covers java methods with examples and explanations. It also goes through the declaration, implementation, types, and its uses.

2022_07_What-is-6.jpg

Contents

What are Java Methods?

A method, in general, is a programming construct, a reusable block of code that performs a specific task. Java Methods in a class are used to define the behavior of its objects. In other words, it describes what operations its objects are capable of performing. 

For instance, you want to enter a few students’ names with roll numbers, and you wish to sort them in ascending order. Here you can create two methods, one for entering student details and the second for sorting the list of students.

There are 2 types of Methods in Java:

Pre-defined Methods

There are several built-in methods in java that are easily and directly accessible. These methods are from java standard libraries which can be Java Class Libraries (JCL) inside the java archive file with JVM and JRE. For example: print() method from class printstream, sqrt() from class math, min() and max() methods etc.

User-defined Methods

User-defined methods are created based on the requirements of the programmer. It has specific rules that have to follow to create a user-defined method.

Here on, we’ll proceed with understanding the working of user-defined methods.

Multithreading in Java
Multithreading in Java
The below article goes through explaining the concepts of Multithreading in Java and its implementation. Let’s begin the tutorial.
Understanding ArrayList in Java
Understanding ArrayList in Java
The below article goes through explaining ArrayList in Java with suitable examples. It covers the creation and operations on ArrayList along with a few methods in it. Let’s begin!
What is StringBuffer in Java?
What is StringBuffer in Java?
The below article goes through the explanation and implementation of the mutable string called StringBuffer in Java along with examples.

How to declare a Method?

Syntax to declare a method in Java:

 
Access_Modifier Return_type Method_Name(Parameter_List)
{
//definition/implementation/body of the method
}
Copy code

1. Access_Modifier: It defines the access type of the method. It means to what extent and where the method can be accessed. It can be public, protected, private, or default. 

FYI, a method with no access specifier is default i.e., package-level.

For more information, Read: Access Modifiers in Java.

2. Return type: The return type or data type can be any of the datatypes (int, char, string, double, etc.). It returns the result to the method call in the respective datatype format.

For more information, Read: Data Types in Java – Primitive and Non-Primitive Data Types Explained.

3. Method_Name: Method name follows the same rule as any programming language naming convention. Names should be in mixed case (uppercase, lowercase, underscore). Use verbs to describe the method. 

4. Parameter_list: The list of parameters/arguments comes inside method round parentheses () separated by commas. If there are no parameters, it means, it’s a non-parameterized method that doesn’t pass any value to the method definition.

Example:

 
class Circle
{
double radius;
void calculateArea() //method 1 definition
{
double area = 3.14*radius*radius;
System.out.println("Area of circle: " +area);
}
void calculateCircumference() //method 2 definition
{
double circum = 2*3.14*radius;
System.out.println("Circumference of circle: " +circum);
}
}
class Main
{
public static void main(String args[])
{
Circle c = new Circle(); //creating object of class circle
c.radius = 5;
c.calculateArea(); //invokes calculateArea() with object c
c.calculateCircumference(); //invokes calculateCircumference() with object c
}
}
Copy code

Output:

output1

Parameterized Methods

Parameterized methods contain a list of parameters separated by commas with method definition and declaration. Let’s see its implementation with an example.

Example:

 
class SimpleInterest
{
public double calculateSI(double p, double r, double t) //parameterized methods
{
return p*r*t;
}
}
class Main
{
public static void main(String args[])
{
SimpleInterest si = new SimpleInterest();
double interest = si.calculateSI(20000.5, 0.8, 1.4); //sending values to the method
System.out.println("The interest calculated is: " +interest);
}
}
Copy code

Output:

output2

How does a method call work?

Let’s take the above program, which calculates simple interest. Here, when the compiler comes to the statement where the method calculateSI() gets invoked. It tries to find a method with the name caculateSI() inside class SimpleInterest as the method is invoked with an object of class SimpleInterest.

While searching for the method in the class, it matches the method name, number, and type of parameters in the method declaration. In finding the correct method, the control of the program branches to the method. Then the actual parameters are mapped onto the formal parameters.

Consider the two statements below.

public double calculateSI(double p, double r, double t) //formal parameters

double interest = si.calculateSI(20000.5, 0.8, 1.4); //actual parameters

The formal parameter 20000.5 is copied into principal p, 0.8 into rate r, and 1.4 into time t. Hence, internally the compiler reads the statements like:

p=20000.5 //principal

r=0.8 //rate

t=1.4 //time

FYI, these variables are local variables for the method. Only the values are copied from actual parameters into formal parameters.

Returning values from a method

Take the Simple Interest example here as well.

The return statement should preferably be the last statement of a method as the control execution jumps to the calling method as soon as the return statement is encountered. The value returned to the calling method must be captured on a type compatible with the return type of the method.

return p*r*t;

Therefore, the value returned from calculateSI() is captured in the variable interest of the double type.

double interest = si.calculateSI(20000.5, 0.8, 1.4); 

Rules for returning values from a method:

  1. The value returned from a method must match its return type. Else the compiler will generate an error.
  2. The value being returned to the calling method is a local value and will be lost as soon as we exit the method. Therefore, this value must be caught in the calling method in a type compatible with the return type of the method.

Why use Methods?

  1. It facilitates code reusability by creating various methods or functions in the program.
  2. It also improves readability and accessibility to a particular code block.
  3. Methods creation makes it easy to debug for the programmers.

Conclusion

Hope the above article helped you understand the Java Methods better and clearer. If you have any queries feel free to reach out to us on the link below. We’d love to answer your queries with an explanation. Happy learning!

Top Trending Tech Articles:
Career Opportunities after BTech | Online Python Compiler | What is Coding | Queue Data Structure | Top Programming Language | Trending DevOps Tools | Highest Paid IT Jobs | Most In Demand IT Skills | Networking Interview Questions | Features of Java | Basic Linux Commands | Amazon Interview Questions
About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio