Method In Java: Welcome to another new core Java tutorial series post. In this article, we will learn about Java methods in detail, like how we can define the Java method & how we can use the Java method in your Java program with the help of real-time examples.
Java is a widely used object-oriented programming language that has gained immense popularity due to its robustness, platform independence, and security features. Java supports various programming paradigms, including procedural, functional, and object-oriented programming.
Java’s object-oriented programming approach is based on principles of abstraction, encapsulation, inheritance, and polymorphism. One of the key aspects of Java programming is its support for methods, which are a fundamental building block of any Java program.
In Java, a method is a block of code that performs a specific task and can be called by other program parts. Methods in Java are used for code reusability, modularization, and abstraction.
In this article, we will explore the basics of methods in Java, how to define them, call them, and use them in a Java program. We will also discuss different types of methods, method parameters, and return values.
Define Method In Java
In Java, a method is a block of code that performs a specific task and can be called by other parts of a Java program. Methods are a fundamental building block of Java programming and are used for code reusability, modularization, and abstraction.
The methods consist of a method signature and a method body. The method signature includes the method’s name, return type, and parameters, while the method body contains the code that performs the specific task.
When a method is called, the program executes the code in the method body, and the method may return a value or not, depending on the return type. Methods in Java can be defined inside a class and accessed only by objects of that class or by the class itself.
They can also be defined with different access modifiers, such as public, private, and protected, which control their accessibility from other parts of the program.
Type Of Method In Java
There are mainly two types of methods available in Java Based on the Creation or availability. These methods are categorized according to some attributes. Does a user define the method, or is the method available in the standard library?
Based on that, methods divided into two types, that is:
- Standard Library Methods
- User-Defined methods
Standard Library Method In Java
The Standard Library Methods methods are nothing but the built-in methods, which are already available inside the Java standard libraries, which come with the Java Class Library (JCL) in a Java archive (*.jar) file with JVM and JRE.
Some Examples of Standard Library Methods are:
- Print(): This method is available inside the java.io.PrintSteam package. This print(“….”) method prints in the console. Whatever you will write inside the quotation marks will print inside the console.
- Sqrt (): This method belongs to the math class. It will return the square root of the given number.
User-Defined Method In Java
A user-defined method in Java is a method that the programmer creates to perform a specific task within a Java program. Unlike built-in methods already included in Java, user-defined methods are created by the programmer and tailored to the program’s specific needs.
How To Create Method In Java?
Creating a method in Java involves defining the method’s name, return type, and parameters. The method’s name should describe the task it performs, while the return type specifies the data type it returns. The parameters are used to pass values to the method, which the method can then use to perform its task.
If we try to understand the components of a method, then we will find mainly five components in methods, and those are:
A. Modifier: By using Access Modifiers, we define the access types. That means where we can access the method. In Java, we have four different access specifiers are there:
- Public: that means we can access the method all over the application
- Protected means that methods are accessible within the class and in its subclasses.
- Private: That method is accessible within the class only.
- Default: If you do not define access specifiers to a method, Java programming language takes default as an access specifier. These methods are accessible within the class and the package.
B. Return Type: It represents what type of value that specific method will return, and sometimes it may be void also. At that time, it will not return anything.
C. Method Name: We are defining a method name with this. And by using the method name, we can access that specific method.
D. Parameter list: This Field is used to pass some values to the method. If you give more than one value to a method, then we use a comma to separate between two parameters. For Each parameter, We have to mention the data type and variable name within an unclosed parenthesis. If no parameter exists, then we have to use empty parenthesis.
E. Method Body: This is the area between two braces. Whatever operation you need to perform, those codes or statements should be written inside the braces.
Syntax of Method
<access_modifier> <return_type> <method_name>( list_of_parameters) { //body }

From the above image, you can notice we have the following:
- public static − modifier
- int − return type
- methodName − the name of the method
- a, b − formal parameters
- int a, int b − list of parameters
How to Name a Method ( Method Naming Convention )
The method name is always a single word; sometimes, the name begins with a lowercase verb followed by an adjective or noun. There is a naming convention for methods like after the first-word first letter of words should be in the capital letter. For Example softwareTestingo, findElement
Note: The method must have a unique name within the class, but sometimes a class can have multiple methods with the same name but different parameters, called method overloading.
How to Call Java Method
Suppose you have defined a method, and later, you want to use that method. So, to use that method, you need to call that method. Let’s understand how to call a method.
myMethod();
This statement is called myMethod(), which was declared earlier.
- While Java executes the program code, it encounters myMethod(); in the code.
- The execution then branches to the myFunction() method and executes code inside the method’s body.
- After the execution of the code inside the method body, the program returns to the original state and executes the next statement.
Java Method Example
package java_Basics; public class Method_Example { public static void main(String[] args) { System.out.println("Going to Call static method myMethod()"); // method call myMethod(); System.out.println("myMethod was executed successfully!"); } // method definition private static void myMethod(){ System.out.println("Printing from inside myMethod()!"); } }
Various Other Method Types in Java
But if we are looking based on the purpose and functionality, we can find several types of methods in Java. Here we tried to list some of the most common types of methods in Java are:
Instance Methods: These are the most common types of methods in Java and are associated with an instance of a class. They are used to access and modify instance variables and perform specific tasks related to the object. Instance methods are defined without the static keyword and can access non-static variables and methods.
package com.softwaretestingo.Basic; class Class_Rectangle { private int length; private int width; public void setDimensions(int len, int wid) { length = len; width = wid; } public void getArea() { int area=length * width; System.out.println("The Area is: "+area); } } public class InstanceMethodEx { public static void main(String[] args) { Class_Rectangle obj=new Class_Rectangle(); obj.setDimensions(10, 20); obj.getArea(); } }
Static Methods: These methods are associated with a class rather than an instance of a class. They are used to perform tasks that do not require access to instance variables or methods. Static methods are defined using the static keyword and can only access static variables and methods.
package com.softwaretestingo.Basic; public class StaticMethodEx { //Static Variable static int a=10; //Static Method static void display() { System.out.println("The Static Value Of a Is: "+a); } public static void main(String[] args) { display(); } }
Constructors: Constructors are special methods used to initialize objects when they are created. They have the same name as the class and do not have a return type. Constructors can be overloaded, allowing a class of multiple constructors with different parameters.
package com.softwaretestingo.Basic; class cEx { String name; int id; public cEx(String name, int id) { this.name=name; this.id=id; } } public class ConstructMethodEx { public static void main(String[] args) { cEx obj=new cEx("SoftwareTestingo", 5); System.out.println("Name :" + obj.name + " and Id :" + obj.id); } }
Getter and Setter Methods: Getter methods are used to retrieve the value of an instance variable, while setter methods are used to set or modify the value of an instance variable. These methods are often used to ensure encapsulation and data hiding in object-oriented programming.
These two getters and setter methods are two different types of Instance methods.
The accessor method (Getters), also known as a getter, enhances the code’s security and protection level. This method returns the value of a specific data type, such as int, String, double, float, etc., to allow access to the data. To facilitate the program’s implementation, the getter usually begins with the word “get” followed by the variable name.
The mutator method (Setters) sets the value of variables used in a class’s programs. This method typically begins with the word “set” followed by the variable name. Both the getter and setter methods facilitate the programmer in setting and retrieving the value of a particular data type. It is recommended that the first letter of the variable name be capitalized in both the getter and setter methods.
Accessor and mutator are mainly used to access or set the value for the private member of the class in the main method.
package com.softwaretestingo.Basic; class accessormutator { //private variable private int value=10; // Mutator method (setter) public void setValue(int a) { // return balance + a; value=value+a; } // accessor method (getter) public int getValue() { return value; } } public class GettersSettersEx { public static void main(String[] args) { accessormutator obj=new accessormutator(); //setting new value obj.setValue(30); System.out.println("Your Value : "+obj.getValue()); } }
Void Methods: Void methods do not return any value and are used to perform a specific task without returning a result.
package com.softwaretestingo.Basic; public class VoidMethodEx { public static void displayValue() { System.out.println("displayValue void method called"); } public static void main(String[] args) { displayValue(); } }
Return Methods: Return methods are used to perform a specific task and return a value. The return type is specified in the method signature, and the method must return a value of that type.
Abstract Methods: Abstract methods are defined in abstract classes and do not have a method body. They are used to define a method signature that any subclass of the abstract class must implement.
package com.softwaretestingo.Basic; abstract class operations { abstract public void printinfo(); } class addition extends operations { public void printinfo() { int a=110; int b=20; System.out.println("The Sum Of Values : "+(a+b)); } } class subsctraction extends operations { public void printinfo() { int a=110; int b=20; System.out.println("The Substraction Of Values : "+(a-b)); } } public class Arithmatic_OperationEx { public static void main(String[] args) { operations obj=new addition(); obj.printinfo(); operations obj1=new subsctraction(); obj1.printinfo(); } }
Final Methods: Final methods cannot be overridden by subclasses and are used to ensure that a method’s implementation cannot be changed.
package com.softwaretestingo.Basic; class Show { //final method public final void show() { System.out.println("Inside final method"); } } class FinalMethodTest extends Show { //try to override final method public void show() { System.out.println("Inside overridden final method"); } } public class FinalMethodEx { public static void main(String[] args) { //creating object of FinalMethodTest Class FinalMethodTest obj = new FinalMethodTest(); //method call obj.show(); } }
In Java, you can not override the final method; if you try to do so, then you will get the below exception:
Exception in thread "main" java.lang.IncompatibleClassChangeError: class com.softwaretestingo.Basic.FinalMethodTest overrides final method com.softwaretestingo.Basic.Show.show()
Native Methods: Native methods are written in a language other than Java and are used to access system resources or perform tasks that are not possible in Java.
Understanding the different types of methods in Java is essential for writing efficient and effective code. Each type of method has its specific purpose and functionality and can be used to perform specific tasks in a Java program.
Please write comments if you find anything incorrect or if you want to share more information about the above-discussed topic.
What are methods in Java?
A method in Java is a set of instructions that can be called for execution using the method name. A Java method can take in data or parameters and return a value – both parameters and return values are optional. Methods can be public, private or protected.
How many types of methods are there in Java?
In Java, we have 2 types of methods: Standard Library Methods & User-Defined methods.
What is the method type in Java?
A method is a collection of statements that perform some specific task and return the result to the caller. A method can perform some specific task without returning anything. Methods allow us to reuse the code without retyping the code.
What is a static method in Java?
Static Method in Java belongs to the class and not its instances. A static method can access only static variables of the class and invoke only static methods of the class.
Leave a Reply