Introduction to Methods in Java
A method in java can be defined as a set of logical java statements written in order to perform a specific task. They provide a way to reuse code without writing the code again. In Java, any method should be part of a class that is different from Python, C, and C++. The existence of methods is not possible without a java class. Here is the list of components involved while creating java methods:
Components for Creating Java Methods
Here is the list of components involved while creating java methods:
- Access Modifier: In java, there exist four different types of access modifiers:
- Public: Methods declared as public are accessible from all classes within an application.
- Protected: Methods declared as protected are accessible from the class within which it is defined and all subclasses of that class.
- Private: Methods declared as private are only accessible from the class within which it is defined.
- Default: Methods declared as default are accessible from the class within which it is defined and from classes declared within the same package as the class enclosing the method.
- Return Type: This contains the data type of the value the method is supposed to return or it is void if the method does not return anything.
- Method Name: This is the named assigned to the method, which may or may not be unique. It is to be noted that the method name should be verbs and words used show follow camel case notation.
- Parameters: This includes a list of input parameters separated by commas with their data types. If the method does not require any input parameters then () is used.
- Exceptions: In case a method may throw one or more exceptions, we can list exceptions separated by commas.
- Method Body: It is the programming content enclosed between braces. The method body contains one or more logical statements for executing a particular task.
Syntax:
Here is a basic syntax of methods:
//declare Enclosing class
public class Myclass{
//declare java method
public String concat(String s1, String s2){
// combine two strings with space
String s3= s1 + " " + s2 ;
//return resulting string
return s3;
}
}
Types of Methods in Java
Methods can be categorized in the following two types:
- Build-in Methods: These methods are available in the java library and does not need to be created by a developer. For example max() method present in Math class in java.
- User-defined Methods: These methods are explicitly defined by a developer in java classes.
Calling a Java Method
When a method is called by a calling program, the control goes into the method body. After control goes to method body, it returns to the calling program under the following three conditions:
- All statements written inside the method body are executed successfully.
- Any return statement is encountered.
- An Exception is thrown.
Static methods are called using class name and non-static methods are called using object instance.
Example #1
Now we will see java code examples show how methods are declared and called using java. In this example, we will see how to create a static method and how is it called.
4.8 (8,018 ratings)
View Course
Code:
package com.edubca.methods;
public class MethodDemo{
public static int getMaximum(int a , int b){
if(a>b){
return a;
}else {
return b;
}
}
public static void main (String args[]){
int maxvalue1 = getMaximum(10,23);
System.out.println("Out of 10 and 23, " + maxvalue1 + " is greater" );
int maxvalue2= getMaximum(40,20);
System.out.println("Out of 40 and 20, " + maxvalue2 + " is greater" );
}
}
Output:
Example #2
In the next example, we will see how to call non–static methods.
Code:
package com.edubca.methods;
public class MethodDemo{
public int getMinimum(int a , int b){
if(a<b){
return a;
}else {
return b;
}
}
public static void main (String args[]){
MethodDemo demo =new MethodDemo();
int minvalue1 = demo.getMinimum(10,23);
System.out.println("Out of 10 and 23, " + minvalue1 + " is smaller" );
int minvalue2= demo.getMinimum(40,20);
System.out.println("Out of 40 and 20, " + minvalue2 + " is smaller" );
}
}
As we can see above an instance of an enclosing class is required to call a non-static method. The above code will produce the following output:
Output:
Example #3
In the next example, we how to create methods throwing exceptions.
Code:
import java.io.*;
package com.edubca.methods;
public class MethodDemo{
public void mymethod() throws IOException{
throw new IOException("IO Exception occurred...");
}
public static void main (String args[]){
MethodDemo demo =new MethodDemo();
try{
demo.mymethod();
}catch(Exception e){
e.printStackTrace();
}
}
}
As we can see from the above code, whenever a method throws an exception caller of the method must handle exception using try-catch or any other suitable error handling mechanism. The above code shows the below output on screen:
Output:
Conclusion
From the above article, we have a clear idea about methods in java. Therefore will the help of methods we can achieve any task. Using methods make our code reusable and easy to test, understand and debug.
Recommended Articles
This is a guide to Methods in Java. Here we discuss the types of methods and list of components involved while creating java methods along with examples and its code implementation. You may also look at the following articles to learn more –