Functions in Java

 Methods

Methods in Java are the same as functions in other programming languages. It will execute a block of code whenever it is being called.

Syntax

--Declaring a method ---

Datatype methodname(){

//block of code

}

--calling a method--

methodname()

 

Types of Methods

1.   Method with parameter without return type.

2.   Method without parameter without return type.

3.   Method with parameter with return type.

4.   Method without parameter with return type.

 

Parameters and Arguments

They are the values passed during the program's run time.

Java Scope

In Java, variables are only accessible inside the region they are created. This is called scope.

Note: static method, which means that it can be accessed without creating an object of the class, unlike public, which can only be accessed by objects


 method with parameter without return type.


package Methods;


public class method2 {


public static void add(int a, int b) {

int s = a;

int p = b;

int c = s+p;

System.out.println(c);

}

public static void main(String[] args) {

add(50,20);

}

}


Method with parameter with return type.

package Methods;


public class method_3 {



static int add(int c, int d) {

return c+d;

}


public static void main(String args[]) {

int m = add(20,30);

System.out.println(m);

}


}



package Methods;

class Methods {

//Method without parameter without return type

public void add() {

int a = 123;

int b = 10;

System.out.println("Addition : " + (a + b));

}

//Method with parameter without return type.

public void sub(int x, int y) {

System.out.println("Subtraction : " + (x - y));

}


//Method without parameter with return type.

public int mul() {

int a = 123;

int b = 10;

return a * b;

}

//Method with parameter with return type

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));

}


}

//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));

}

}




Post a Comment

0 Comments