Methods in Java Class : Concept in Java
- In Java Class , We can add user defined method.
- Method is equivalent to Functions in C/C++ Programming.
Syntax : Methods in Java Classes
return_type method_name ( arg1 , arg2 , arg3 )
- return_type is nothing but the value to be returned to an calling method.
- method_name is an name of method that we are going to call through any method.
- arg1,arg2,arg3 are the different parameters that we are going to pass to a method.
Return Type of Method :
- Method can return any type of value.
- Method can return any Primitive data type
int max (int num1,int num2);
- Method can return Object of Class Type.
Box sum (int num1,int num2);
- Method sometimes may not return value.
void max (int num1,unt num2);
Method Name :
- Method name must be valid identifier.
- All Variable naming rules are applicable for writing Method Name.
Parameter List :
- Method can accept any number of parameters.
- Method can accept any data type as parameter.
- Method can accept Object as Parameter
- Method can accept no Parameter.
- Parameters are separated by Comma.
- Parameter must have Data Type
Example : Method in Java Class
class Box {
double length;
double width;
void setLength(int len)
{
length = len;
}
}
class BoxExample {
public static void main(String args[]) {
Box b1 = new Box();
b1.length = 10;
System.out.println("Before Function Length : " + b1.length);
b1.setLength(20);
System.out.println("After Function Length : " + b1.length);
}
}
Output :
C:zubair>java BoxExample
Before Function Length : 10.0
After Function Length : 20.0
Explanation :
Calling a Method :
- “b1” is an Object of Type Rectangle.
- We are calling method “setLength()” by writing –
Object_Name [DOT] Method_Name ( Parameter List ) ;
- Function call is always followed by Semicolon.
Method Definition :
- Method Definition contain the actual body of the method.
- Method can take parameters and can return a value
-
Nice blog. Loved it. java training in chennai
ReplyDelete