Java Methods
Syntax of a Method
A method is a function written inside a class. Since Java is an object-oriented language, we need to write the method inside some class.Syntax of a method :
returnType nameOfMethod() {
//Method body
}
The following method returns the sum of two numbers
int mySum(int a, int b) {
int c = a+b;
return c; //Return value
}
Calling a Method :
A method can be called by creating an object of the class in which the method exists followed by the method call:
Calc obj = new Calc(); //Object Creation
obj.mySum(a , b); //Method call upon an object
The values from the method call (a and b) are copied to the a and b of the function mySum. Thus even if we modify the values a and b inside the method, the values in the main method will not change.
Void return type :
When we don’t want our method to return anything, we use void as the return type.
Static keyword :
Process of method invocation in Java :
Consider the method Sum of the calculate class as given in the below code :
class calculate{
int sum(int a,int b){
return a+b;
}
The method is called like this:
class calculate{
int sum(int a,int b){
return a+b;
}
public static void main(String[] args) {
calculate obj = new calculate();
int c = obj.sum(5,4);
System.out.println(c);
}
}
Output
9
Note: In the case of Arrays, the reference is passed. The same is the case for object passing to methods.
Example
package com.company;
public class cwh_31_methods {
static int logic(int x, int y){
int z;
if(x>y){
z = x+y;
}
else {
z = (x +y) * 5;
}
x = 566;
return z;
}
public static void main(String[] args) {
int a = 5;
int b = 7;
int c;
// Method invocation using Object creation
//cwh_31_methods obj = new cwh_31_methods();
//c = obj.logic(a, b);
c = logic(a, b);
System.out.println(a + " "+ b);
int a1 = 2;
int b1 = 1;
int c1;
c1 = logic(a1, b1);
System.out.println(c);
System.out.println(c1);
}
}
Output
5 7
60
3
60
3