Methods in Java
Creating Method
public int methodName(int a, int b) {
// method body
return someThings;
}
- public - modifier access type (public, private, protected)
- int - return type
- methodName - name of method
- int a, int b - list of parameters
Example
/** returns the minimum between two numbers */
public int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
Calling Method
public class ExampleMinNumber {
public static void main(String[] args) {
int a = 11;
int b = 6;
int c = minFunction(a, b); // calling method
System.out.println("Minimum Value = " + c);
}
/** returns the minimum of two numbers */
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
The void keyword allows us to create methods which do not return a value.
void - return type
public void methodName(int a, int b) {
// method body
}
Example
public class ExampleVoid {
public static void main(String[] args) {
methodRankPoints(255.7);
}
public static void methodRankPoints(double points) {
if (points >= 202.5) {
System.out.println("Rank:A1");
}else if (points >= 122.4) {
System.out.println("Rank:A2");
}else {
System.out.println("Rank:A3");
}
}
}
If you want the method to return a value, you can use a primitive data type (such as int, double, char, etc.)
Use the return keyword inside the method.
value - return type
public int methodName(int a) {
// method body
return value;
}
public class Triangle {
public static void main(String[] args) {
double area;
area = calculateArea(6, 10);
System.out.println("Area of triangle is " + area);
}
public static double calculateArea(double height, double base) {
return height * base / 2;
}
//create method to calculate round of triangle
}
Example
Methods in Java
By Nur Ratna Sari
Methods in Java
- 66