1.5 Methods/Function in Java.
Method/Function in Java:
-> to implement a task/operation.
-> reusebility.
Syntax:
modifier_ returnType_methodName(arguments)
{
-
- //statement to implement task.
-
return value;
}
Method Argument(parameters):
1. to pass values to method value.
2. multiple arguments can be defined.
3. argType(dataType) argName(identifier)
Method return type:
1. to return values from method body.
2. return type field indicates the type & data/values return by method body.
3. if return type void method body return nothing.
4. method can return only one value.
Note:
A method can not be defined in anothor method body it should be defined only with in the class body.
Example Program 1:
class Program1
{
static void test() //user defined method
{
System.out.println("running test() method");
}
public static void main(String args[]) //main method
{
System.out.println("main method is started");
test(); //method call
test();
System.out.println("main method is ended");
}
}
Example Program 2:
class Program2
{
static void test(int avg1) //user defined function
{
System.out.println("running test() method with int avg");
System.out.println("Argument value is"+ avg1)
}
public static void main(String args[]) //main method
{
System.out.println("main method is started");
test(15); //method call
int x = 7;
test(x); //pass value of x to test method
System.out.println("main method is ended");
}
}
Example Program 3:
class Program3
{
static void test(int avg1, double avg2) //user defined method
{
System.out.println("running test() method with int and double");
System.out.println("first argumet value is"+ avg1);
System.out.println("second argument value is"+ avg2);
}
public static void main(String args[]) //main method
{
System.out.println("main method is started");
test(15, 5.3); //method call
int x = 17;
double y = 7.1;
test(x,y); //pass value of x to test method
System.out.println("main method is ended");
}
}
Example Program 4:
class Program4
{
static int test() //user defined method
{
System.out.println("running test() started");
return 18;
}
public static void main(String args[]) //main method
{
System.out.println("main method is started");
int x = test(); //return value is assigned to x variable
System.out.println("x value is"+ x);
System.out.println("main method is ended");
}
}
Comments
Post a Comment