Giving a method some information
Parameters are values you pass into a method, written inside the brackets with their type:
public class Main {
static void greet(String name, int age) {
System.out.println("Hi " + name + ", you are " + age);
}
public static void main(String[] args) {
greet("Asha", 21);
greet("Ravi", 34);
}
}Output
Hi Asha, you are 21 Hi Ravi, you are 34
Getting an answer back: return
Instead of void, write the type of the answer. return sends the answer back to whoever called the method:
public class Main {
static int square(int n) {
return n * n;
}
static double areaOfCircle(double radius) {
return Math.PI * radius * radius;
}
public static void main(String[] args) {
int s = square(6);
System.out.println(s);
System.out.println(square(3) + square(4));
System.out.printf("%.2f%n", areaOfCircle(2));
}
}Output
36 25 12.57
Think of it like this: A method with
returnis like a juice machine: you put in fruit (the parameters) and get juice back (the return value).
Methods that answer yes or no
public class Main {
static boolean isEven(int n) {
return n % 2 == 0;
}
public static void main(String[] args) {
for (int i = 1; i <= 4; i++) {
if (isEven(i)) {
System.out.println(i + " is even");
}
}
}
}Output
2 is even 4 is even
Remember:
returnends the method straight away. Any code after it in the same block never runs.
Common mistake: If a method says it returns
int, every path through it mustreturnan int, otherwise you get a missing return statement error.