A Java method is a collection of statements that are grouped together to perform an operation. A method in Java is a block of code that, when called, performs specific actions mentioned in it. For instance, if you have written instructions to draw a circle in the method, it will do that task.
You can insert values or parameters into methods, and they will only be executed when called. They are also referred to as functions. The primary uses of methods in Java are:
Two Types of Methods :
1. User-defined Methods : We can create our own method based on our requirements.
2. Standard Library Methods : These are built-in methods in Java that are available to use.
Syntax:
Access_ specifier Return_type Method_name ( Parameter list )
{
// body of method ;
}
Access specifier :
Return type :
Parameter list :
Method body :
This is a Java program that demonstrates different types of user-defined methods. Let's go through each method one by one:
In the main() method, an object of the Methods class is created and the different methods of the class are called to demonstrate their usage.
Overall, this program demonstrates the different types of user-defined methods that can be created in Java and how they can be used in a program.
class Methods { //No Return W/o args public void add() { int a = 123; int b = 10; System.out.println("Addition : " + (a + b)); } //No Return With Args public void sub(int x, int y) { System.out.println("Subtraction : " + (x - y)); } //Return Without Args public int mul() { int a = 123; int b = 10; return a * b; } //Return With Args public float div(int x, int y) { return (x / y); } //Recursion Function public int factorial(int n)//5! =1*2*3*4*5=120 { if(n==1) return 1; else return (n*factorial(n-1)); } /* factorial(5) factorial(4) factorial(3) factorial(2) factorial(1) return 1; return 2*1; return 3*2; return 4*6; return 5*24; * */ } //Type of User Define Methods in Java public class functions { public static void main(String args[]) { Methods o = new Methods(); o.add(); o.sub(123, 10); System.out.println("Muli : "+o.mul()); System.out.println("Division : "+o.div(123,10)); } }
Addition : 133 Subtraction : 113 Muli : 1230 Division : 12.0To download raw file Click Here
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions