Java Methods
A method is a named block of code which you can run many times. Methods make programs short, clear and easy to test. In other languages they are called functions.
Declare and call a method
public class Main {
// method declaration
static void greet() {
System.out.println("Hello from a method!");
}
public static void main(String[] args) {
greet(); // call it
greet(); // call it again
}
}
Output
Hello from a method!
Hello from a method!
Parts of a method
static int add(int a, int b) {
return a + b;
}
| Part | Meaning |
|---|---|
| static | Belongs to the class (we use it in main for now) |
| int | The return type. Use void when nothing is returned |
| add | The name of the method (camelCase) |
| (int a, int b) | The parameters: the inputs |
| return a + b; | Sends the result back to the caller |
Parameters and return values
public class Calc {
static int add(int a, int b) {
return a + b;
}
static double average(int[] numbers) {
int sum = 0;
for (int n : numbers) {
sum += n;
}
return (double) sum / numbers.length;
}
static boolean isEven(int n) {
return n % 2 == 0;
}
public static void main(String[] args) {
int total = add(5, 7);
System.out.println(total);
System.out.println(average(new int[]{70, 80, 95}));
System.out.println(isEven(10) + " " + isEven(7));
}
}
Output
12
81.66666666666667
true false
Pass by value
Java always passes a copy of the value. For a primitive, the original variable can not be changed by the method. For an object or an array the copy is a copy of the reference, so the method can change the object itself.
import java.util.Arrays;
public class Pass {
static void changeNumber(int x) {
x = 100; // changes only the copy
}
static void changeArray(int[] a) {
a[0] = 100; // changes the real array
}
public static void main(String[] args) {
int n = 5;
changeNumber(n);
System.out.println(n);
int[] arr = {1, 2, 3};
changeArray(arr);
System.out.println(Arrays.toString(arr));
}
}
Output
5
[100, 2, 3]
Return early
public class Early {
static String sign(int n) {
if (n > 0) return "positive";
if (n < 0) return "negative";
return "zero";
}
public static void main(String[] args) {
System.out.println(sign(5) + " " + sign(-3) + " " + sign(0));
}
}
Output
positive negative zero
Rules
- A method with a return type must return a value on every path.
- A method can return only one value (use an array, a list or a record for more).
- Give methods verb names:
calculateTotal(),isValid(). - A method should do one job.
Note:
When a method is not static, you call it on an object. You will learn that in Java Classes and Objects. Next: Java Method Overloading and Varargs.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |