How to Define, Create and Execute Java Methods
While writing a program, sometimes we need to perform a certain set of instruction or execute certain functionality repeatedly and instead of writing the set of statements frequently we generalize this statement by setting them in a function or method. Every programming language uses the methodology of methods to make the code simple, easy and robust.
Functions are of Two Types
- Predefined
- User defined
Learn Java from scratch with a tutorial at Udemy.com
Creating the Method:
General Syntax
modifier returnType nameOfMethod(Parameter List)
{
// method body
}
- Modifier defines the access type of the method in a class. There are three type of modifiers and they are the public, private and protected modifiers.
- return type: This specifies the value that the function would return which can be an integer, float, double or character. If the value is void, it means that the function does not return any values. Such functions are called procedures.
- nameofMethod is the function name similar to variables. Generally by coding conventions, function names are given such that it defines their functionality but it is not compulsory.
- Parameter list: This is the list of arguments that the function takes or requires to process the functionality. However, it is optional and may be zero.
- Method Body in between the curly braces is the place where we define the functionality or a set of statements that would execute every time on a function call.
Learn more about Java programming with a tutorial at Udemy.com
Syntax:
public static intfuncName((argument 1, argument 2) { //body }
Example
class Demo { public static in myFirst(int n, int m) { System.out.println(“I am inside the Function”); int max; if(n>m) { max=n; } else { max=m; } return max; }}
Note the “static” keyword is used, but it’s optional. Declaring a function static means that it can be directly called inside the class without creating class objects.
Things to Note
- Variable declared inside the function cannot be used outside the functional scope.
- The return statement in function is a must if the function is not a void type.
- The function can only return single value and the returned value must match with the data type of function that is defined.
- The argument passed must match i.e it should be in the same order as declared in the functions.
Get to know more about Java programming with a tutorial at Udemy.com
Method Calling
To use a defined function, it must be called. When the method is called, the control jumps to the functions and its execution starts until the return statement or closing curly braces are not found.
import java.util.*; import java.lang.*; import java.io.*; class Demo { // Main method public static void main(String[] args) { int a = 4; int b = 6; //Function calls int c = sumFunction(a, b); display(c); } // Returns the sum of the Two numbers public static intsumFunction(int n, int m) { int sum=0; sum= n+m; return sum; } public static void Display(int sum) { System.out(“This function prints the variable”); System.out.println("The Sum is = " + sum); } }
Output
The Sum is = 10
There are two functions present in this example. One function calculates the sum of the two arguments passed to it and returns the result. The display function only prints the result on the console and does not return any value.
The “Main” method is present in every program. It is a compulsory function and is declared static always. Main method is the starting point of execution of the program. All the function calls are made from “main” method.
There are two ways of passing the value to the function:
- Passing the value: The changes made in the function do not affect the value in the main function.
- Passing the reference of the value: The object of the class is passed and the value of the variable is accessed using the object name dot variable name. The change made in this is directly reflected in the variable of that object.
Method Overloading
When a class has two or more methods with the same name but different number of arguments, it is known as method overloading. In such cases the compiler decides which function has to be called, on the basis of arguments passed.
Example
class DemoOverloading{ public static void main(String[] args) { int a = 10; int b = 5; double c = 7.5; double d = 3.4; int result1 = maxFunction(a, b); // Same functions but different parameter types double result2 = maxFunction(c, d); System.out.println("Maximum Value = " + result1); System.out.println("Maximum Value = " + result2); } // function with integer parameters public static intsumFunction(int n1, int n2) { int max; if (n1 > n2) max = n1; else max = n2; return max; } // function with double parameters public static double sumFunction(double n1, double n2) { double max; if (n1 > n2) max = n1; else max = n3; return max; } }
Output
Maximum Value = 10
Maximum Value = 7.5
When the integer value is passed as an argument then “sumFunction(int n1, int n2)” is called, but when a double value is passed then “sumFunction(double n1, double n2)” is called.
Constructors
Constructors are special methods that have the exact same name as the class. They are called automatically when the object of the class is created. They are used to initialize the values. Every class has an object in Java by default and thus the constructor method is present in the program even if we do not create it. We can overload the constructor for our specific purposes.
Example
class MyClass { int x; // the Constructor MyClass(inti ) { x = i; } public static void main(String args[]) { // Objects are created MyClass t3 = new MyClass( 10 ); MyClass t4 = new MyClass( 20 ); System.out.println(t3.x + " " + t4.x); } }
Output
10 20
When the objects are called, the constructors are automatically called with value being passed as argument to them.
Variable Arguments
We can pass the variable argument to the same function. We need to specify the function by an ellipis(…). Only one variable can be specified of variable length and should be the last parameter.
Example:
class Demo { public static void main(String args[]) { // Calling method with variable arguments printMin(34, 1, 5, 6, 45.6); printMin(new double[]{5, 45.6, 3}); } public static void printMin( double... numbers) { if (numbers.length == 0) { System.out.println("No argument passed"); return; } double result = numbers[0]; for (inti = 1; i<numbers.length; i++) if (numbers[i] < result) result = numbers[i]; System.out.println("The min value is " + result); } }
Output:
The min value is 1
The min value is 3
The variable value passed is stored as an array in the variable defined in the function definition. For instance, “numbers” variable in the above example is stored as an array and the value can simply be accessed as done in the case of arrays.
Recommended Articles
Top courses in Java
Java students also learn
Empower your team. Lead the industry.
Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.