Java Tutorial - 29 Methods in Java - StudyViral
Java Tutorial - 29 Methods in Java - StudyViral
A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method's name.
Methods allow us to reuse the code without retyping the code.
The only required elements of a method declaration are the method's return type, name, a pair of parentheses, () , and a body between braces, {} .
The only required elements of a method declaration are the method's return type, name, a pair of parentheses,
()
, and a body between braces, {}
.More generally, method declarations have six components, in order:
- Modifiers—such as
public
,private
,protected - The return type—the data type of the value returned by the method, or
void
if the method does not return a value. - The method name—the rules for field names apply to method names as well, but the convention is a little different.
- The parameter list in parenthesis—a comma-delimited list of input
parameters, preceded by their data types, enclosed by parentheses,
()
. If there are no parameters, you must use empty parentheses. - An exception can be part of method header section after parentheses () and before opening brace {.
- The method body, enclosed between braces—the method's code, including the declaration of local variables, goes here.
Example :
public class DemoMethods {
//declaration of method
public static void myMethod() {
System.out.println("Hye it's my method");
}
//declaration of method
public void myMethod1() {
System.out.println("Hye now i need Object to call this method");
}
public static double adding1(double a, double b) {
double c = a+b;//30
return c;
}
//declaration of method
public int adding2(int a,int b,int c) {
int d = a+b+c;//17
return d;
}
public static void main(String[] args) {
myMethod();//calling
DemoMethods dm = new DemoMethods();
dm.myMethod1();
System.out.println("Retutn double :: "+adding1(10.0,20.0));
System.out.println("Retutn int :: "+dm.adding2(5,4,8));
}
}