What are Methods, Functions, and Procedures in Java? Are they Identical or Distinct?
In computer programming, developers interchangeably use the terms methods, functions, and procedures. In some programming perceptions, programmers name it as methods in Java, procedures in low-level languages, and functions in scripting languages. Let’s explore these terms in Java and their differences in this article.
Methods
A method is a block of code associated with an object that performs certain tasks when it is called. It is part of a class. We can pass data into methods that are known as parameters. Methods should be created within a class. Java also has constructor methods. A constructor is a special method that creates an object of a class.
Declaration of methods
As we said earlier methods should be declared within a class. The following syntax is used to declare a method in Java.
return_type method_name(parameters list){
//method body
}
For example,
public int addNumbers (int a, int b){
//method body
}
Here Public is an access modifier, int is the return type, addNumbers is a method name, and finally, int a & int b are parameters passed into the method addNumber.
There are 6 components included in the method declaration.
Access modifier
It is used to specify the method's access type. There are 4 types of access modifiers in Java.
i) private - Within the class where it is defined, you can access it.
Here, we can see an example, including two classes A and B. Class A consists of private data members and private methods. When we try to access these private members from outside the class, it will throw a compilation error.
class A{
private int data=40;
private void msg(){System.out.println("Hello");}
}
public class B{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
ii) public - It is accessible from any class.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:
iii) default - If we don't provide any other specifiers, the Java compiler will use this one as the default access specifier. It can only be accessed from the package where it is declared.
In this example, two packages, pack, and mypack, have been generated. Since the A class is not public and hence cannot be accessible from outside the package, we are accessing it from outside the package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the aforementioned illustration, class A's default scope prevents its method msg() from being accessible from outside the package.
iv) protected - accessible only inside the same package or through additional subclasses within a different package.
The two packages pack and mypack were developed for this example. Since the pack package's A class is public, it can be accessed from elsewhere. However, because this package's msg method is marked as protected, the only inheritance will allow outsiders to access it.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:
Return type
It aids in determining the return value of the methods; depending on the requirements of the program, it may be an int, char, or long. If the program isn't returning any values, it may be void.
public class ReturnTypeTest1 {
public int add() { // without arguments
int x = 30;
int y = 70;
int z = x+y;
return z;
}
public static void main(String args[]) {
ReturnTypeTest1 test = new ReturnTypeTest1();
int add = test.add();
System.out.println("The sum of x and y is: " + add);
}
}
Output:
Method name
It is used to name the method. It is crucial to name your methods correctly because this will make it easier for the programmer to assess your program and for the debugging processes.
public class Main {
static void myMethod() {
// code to be executed
}
}
Here, myMethod() is the method name.
Parameter list
It indicates the list of arguments (data type and variable name) that will be used in the method. It is used to send input parameters from the main function to our methods. If there is no variable accessible as a parameter, methods should be encased in brackets.
public class Main {
static void myMethod(String fname, int age) {
System.out.println(fname + " is " + age);
}
public static void main(String[] args) {
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
}
Output:
Here, fname, and age are parameters. While Liam, Jenny, and Anja are arguments.
Method signature
Don’t worry about this. It is a combination of the method name and parameter list.
public void setMapReference(int xCoordinate, int yCoordinate)
{
//method code
}
In the aforementioned example, the method signature is setMapReference (int, int). In other words, it consists of the method name and a list of two integer parameters.
Method body
In this, the set of instructions that the method will execute is mentioned within curly brackets.
public class MethodsExample{
//Creating a Method
public int addNumbers(int x, int y){
int addition = x+y;
return addition;
}
public static void main(String args[ ]){
int i=10;
int j=25;
MethodsExample obj = new MethodsExample();
int result = obj.addNumbers(i,j);
System.out.println("Sum of x+y = " + result);
}
}
Output:
Call a method
A method can be called by placing its name in parenthesis and a semicolon. The example below will create an example method named exMethod() and call it to print a text.
public class Example{
static void exMethod(){
System.out.println("We just called a method to print this!");
}
public static void main(String args[ ]){
exMethod(); //Calling the method
}
}
Output:
Types of Methods
Pre-defined methods
Predefined methods are built-in methods in Java that the Java class libraries have previously defined, as the name implies. This indicates that they don't need to be defined and can be called and used anywhere in our software. There are various predefined methods, each of which is defined inside its corresponding class, including length(), sqrt(), max(), and print().
The following example makes use of the predefined methods main(), print(), and sqrt ().
public class Example{
//Using the main method
public static void main(String args[ ] ){
//Using the print and sqrt methods
System.out.println("The Square root is: " + Math.sqrt(25));
}
}
Output:
User-defined method
User-defined methods are specific methods that the user has defined. These techniques can be adjusted and modified based on the circumstances. Here is an illustration of a user-defined method.
public class Example{
//Creating a method
public int subNumbers(int x, int y){
int subtract = x - y;
//Returning the value
return subtract;
}
public static void main(string[ ] args){
int num1 = 57;
int num2 = 22;
//creating an object of Example class
Example obj = new Example();
//Calling the method
int outcome = obj.subNumbers(num1, num2);
System.out.println("Outcome is: " + outcome);
}
}
Output:
Use cases of Methods:
Methods encourage the reuse and maintainability of code. Code reusability means defining the code once, and using it many times.
A complicated program can be divided up into simpler code segments.
It makes code more readable.
Functions
Functions are subroutines that do have a return value. A function in computer programming languages denotes a collection of different instructions that take input from users and carry out certain tasks. These functions then carry out their respective tasks within the program and return a value.
Simply said, computer programs use functions to calculate anything from the input they are given. Its name or term thus comes from mathematics. These are the principles of computer programming, and they may be predefined or created by the user. A block of code inside a function uses it to carry out specific responsibilities. Unlike a method, a function is not associated with an object.
Math.pow() is an illustration of a built-in Java function. This mathematical operation takes two double parameters and outputs the first parameter raised to the power of the second parameter. 'double' is the return type.
import java.lang.*;
public class MathDemo {
public static void main(String[] args) {
// get two double numbers
double x = 2.0;
double y = 5.4;
// print x raised by y and then y raised by x
System.out.println("Math.pow(" + x + "," + y + ")=" + Math.pow(x, y));
System.out.println("Math.pow(" + y + "," + x + ")=" + Math.pow(y, x));
}
}
Output:
Stored functions in Java
A stored function is a group of Java commands that accomplish a certain operation. It is similar to a stored procedure in that it simply takes input arguments and returns a single value.
Java stored functions in Java DB refer to Java code that is executed as stored functions within the database. Stored functions in Java are database-side JDBC (Java Database Connectivity) routines.
import java.sql.*;
public class IsPrime {
public static void main(String[] args) {
Connection con=null;
try
{
con= DriverManager.getConnection("jdbc:mysql://localhost:3306/gfg","root","root");
CallableStatement cs=con.prepareCall("{?=call isPrime(?)}");
cs.registerOutParameter(1, Types.BOOLEAN);
cs.setInt(2,5);
cs.execute();
System.out.println("Result : "+cs.getInt(1));
}
catch (Exception e)
{
System.out.println(e);
}
finally {
try
{
con.close();
}
catch (SQLException e)
{
System.out.println(e);
}
}
}
}
Output:
Advantages of stored functions
The database contains stored functions that can be called as and when needed.
Multiple apps can use the database itself to hold business and database logic.
lowers traffic. No need to transmit the group of questions over the internet. The database stores the functions, and the results can be fetched by calling the stored functions.
As a result, they can be quickly executed because they are only ever compiled once.
Procedures
Procedures are a collection of different instructions that are used to carry out a certain task. Procedures don’t return any value. If you want a Java method to be a procedure, specify void as the return type.
For example, System.out.println() is a built-in procedure in Java. Without returning a value, this procedure just outputs its parameter to the console.
// Java code to illustrate
// System.out.println();
import java.io.*;
class GFG {
public static void main(String[] args)
{
System.out.println("Welcome");
System.out.println("To");
System.out.println("GeeksforGeeks");
}
}
Output:
Stored procedure in Java
Java stored procedures in Java DB refer to Java code that is executed as a stored procedure (or procedure) within the database. Stored procedures in Java are database-side JDBC (Java Database Connectivity) routines.
The procedure code is defined in a Java class method and stored in the database. This is executed using SQL. The procedure code can be with or without any database-related code.
A stored procedure is a collection of SQL statements that are kept together in the database as a single unit of code that may be used repeatedly without rewriting the queries. A stored procedure accepts input and output parameters as well as numerous output values.
Types of stored procedure
Nested connections
The transaction used by this kind of operation is the same as the one used by the SQL statement that is called it. Using the connection URL syntax jdbc:default:connection, the procedure code connects using the same connection as the parent SQL. An example code bit to establish a connection is as follows.
Connection c = DriverManager.getConnection("jdbc:default:connection");
The connection URL attributes are not available for this type, please note.
For example, Create a Java method, compile it, and store the procedure in the database.
public static void testProc(int iParam1, String iParam2, int [] oParam)
throws SQLException {
String connectionURL = "jdbc:default:connection";
Connection conn = DriverManager.getConnection(connectionURL);
String DML = "UPDATE TEST_TABLE SET NAME = ? WHERE ID = ?";
PreparedStatement pstmnt = conn.prepareStatement(DML);
pstmnt.setString(1, iParam2);
pstmnt.setInt(2, iParam1);
int updateRowcount = pstmnt.executeUpdate();
oParam [0] = updateRowcount;
} // testProc()
The code is written and then compiled in a Java class, such as JavaStoredProcs.java. Within a class, any number of process methods can be developed.
Three parameters make up the procedure method. The first two (iParam1 and iParam2) are IN parameter modes, whereas the third is an OUT parameter mode. Each OUT and INOUT parameter must be supplied in the procedure method as an array, and only the first element of the array is used (i.e., mapped) as the procedure parameter variable. Take note that the OUT parameter is specified as an array.
The procedure uses a nested connection. Any SQL exception that is thrown can be handled either within the caller program or within the procedure method in this scenario.
The CREATE PROCEDURE statement is used to create the procedure in the database. This command can be executed interactively with ij or from a Java program using java.sql.Statement interface provided by the JDBC API.
Syntax:
CREATE PROCEDURE procedure-Name(ProcedureParameters)ProcedureElements
procedure-Name: if not supplied, the default schema is used to build the procedure with that name as it appears in the database.
ProcedureParameters: Specifies the data type, an optional name, and the parameter mode (IN, INOUT, or OUT). The data type is one used in databases. Long column types (such as Long Varchar, BLOB, etc.) are not supported by Java DB in methods. A parameter can be omitted.
ProcedureElements: This must contain the following three elements, and can have additional optional ones.
LANGUAGE JAVA. This is the only value.
PARAMETER STYLE JAVA. This is the only value.
EXTERNAL NAME. This specifies the Java method to be called when the procedure is executed and takes the form ClassName.methodName Optional, procedure elements:
DYNAMIC RESULT SETS integer
DeterministicCharacteristic
EXTERNAL SECURITY
MODIFIES SQL DATA (the default), CONTAINS SQL, READS SQL DATA, NO SQL (a procedure without any database-related code)
Non-nested connection
A new database connection is used for this kind of procedure. A distinct transaction from the caller SQL is used to execute the procedure.
In this illustration, the Java process uses a different connection and database than the one the caller program uses. A value for the OUT integer parameter is the procedure's output.
Make the procedure code and build it.
public static void testProc4(int [] retval)
throws SQLException {
String connectionURL = "jdbc:derby:testDB2";
Connection conn = DriverManager.getConnection(connectionURL);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM ID_TABLE");
int nextid = 0;
while(rs.next()) {
nextid = rs.getInt("ID");
}
retval[0] = nextid;
conn.close(); // alternative: shutdown the database.
} // testProc4()
In the database, create the procedure.
CREATE PROCEDURE PROC_NAME_4(OUT paramname INTEGER)
LANGUAGE JAVA
EXTERNAL NAME 'JavaStoredProcs.testProc4'
PARAMETER STYLE JAVA
READS SQL DATA;
The procedure element READS SQL DATA makes it clear that only SELECT statements may be used with the SQL in-process technique.
Invoke the procedure in the client program.
private static void runStoredProc4(Connection conn)
throws SQLException {
String proc = "{call PROC_NAME_4(?)}";
CallableStatement cs = conn.prepareCall(proc);
cs.registerOutParameter(1, java.sql.Types.INTEGER);
cs.execute();
int oParamData = cs.getInt(1); // proc output value
} // runStoredProc4()
Difference between function and method
Difference between function and procedure
Difference between Stored procedure and Stored function
Finally
Method versus Function versus Procedure.
A method is a function used with and applied to objects in object-oriented programming languages. Within a class, methods are specified and have the option of returning a value (void). It is defined by putting the method's name in parentheses ().
A subroutine that returns a value is called a function. In the past, functions were designed to carry out computations with given inputs and deliver the results of the calculations without having any adverse effects.
A program that returns no value is referred to as a procedure. A procedure is specified with a specific keyword called procedure in earlier programming languages like Pascal. The purpose of procedures is to carry out tasks using given inputs and have unintended consequences (e.g. logging).
A stored function is a set of Java statements that perform some operation and return a single value.
Java code invoked within the database is a stored procedure (or procedure). Java-stored procedures are database-side JDBC (Java Database Connectivity) routines.
In the end, the methods, functions, and procedures are identical with a few minor differences.
Comments
Post a Comment