Java course menu
Java Methods: Defining, Calling, Parameters and Return Values
Learn Java methods: defining static methods, calling them, parameters and arguments, return types and void, returning early, boolean methods, the method signature, and how to write small single-purpose methods.
On this page
A method is a named block of code that performs one task. You define it once and call it whenever you need it. Methods make programs shorter, easier to test and easier to read, because each piece of work has a name. (Other languages call them functions; in Java every function lives inside a class, so it is called a method.)
You have already written one method in every program: main.
Defining and calling a method#
public class Main {
static void greet() {
System.out.println("Welcome to Laviyx Learn!");
}
public static void main(String[] args) {
greet();
greet();
}
}Welcome to Laviyx Learn!
Welcome to Laviyx Learn!A method definition has:
- modifiers: here
static, which means the method belongs to the class and can be called frommainwithout creating an object (you will learn about non-static methods in Classes and Objects); - a return type:
voidmeans it returns nothing; - a name in
camelCase, usually a verb; - a parameter list in parentheses;
- a body in braces.
Parameters#
Parameters receive the values (arguments) passed in a call:
public class Main {
static void greet(String name, int visits) {
System.out.println("Hello, " + name + "! Visit number " + visits + ".");
}
public static void main(String[] args) {
greet("Asha", 3);
greet("Ravi", 1);
}
}Hello, Asha! Visit number 3.
Hello, Ravi! Visit number 1.Arguments match parameters by position, and each must have a compatible type. greet(3, "Asha") does not compile.
Returning a value#
A method with a return type sends a result back with return:
public class Main {
static double rectangleArea(double width, double height) {
return width * height;
}
public static void main(String[] args) {
double area = rectangleArea(4.5, 2);
System.out.println("Area: " + area);
System.out.println("Twice: " + 2 * rectangleArea(3, 3));
}
}Area: 9.0
Twice: 18.0The call rectangleArea(4.5, 2) is an expression whose value is the returned result, so you can store it, print it or calculate with it.
return also ends the method immediately, which is handy for special cases:
public class Main {
static int safeDivide(int a, int b) {
if (b == 0) {
return 0; // early return for the special case
}
return a / b;
}
public static void main(String[] args) {
System.out.println(safeDivide(10, 3) + " " + safeDivide(5, 0));
}
}3 0The compiler checks that every path through a non-void method returns a value: "missing return statement" means one path does not.
Methods that answer a question#
Methods returning boolean are usually named like a question:
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++) {
System.out.println(i + (isEven(i) ? " even" : " odd"));
}
}
}1 odd
2 even
3 odd
4 evenOrder does not matter#
Unlike C and C++, Java methods can be defined in any order inside a class: main can call a method defined below it, with no declarations needed.
The method signature#
A method's name plus its parameter types form its signature, for example rectangleArea(double, double). Two methods in the same class may share a name if their signatures differ; that is overloading, covered in Method Overloading.
Writing good methods#
- One task per method. If describing it needs "and", consider splitting it.
- Name it with a verb (
printReport,calculateTax) or a question forbooleanresults (isValid,hasStock). - Keep it short enough to read in one screen.
- Prefer returning results over printing them, so callers decide what to do with the value.
Common mistakes#
Practice#
Practice exercise
Write celsiusToFahrenheit(double c) that returns c * 9 / 5 + 32, and describe(double c) that prints, for example, 30.0 C = 86.0 F. Call describe for 0, 37 and 100.
Show solution
public class Temperatures {
static double celsiusToFahrenheit(double c) {
return c * 9 / 5 + 32;
}
static void describe(double c) {
System.out.println(c + " C = " + celsiusToFahrenheit(c) + " F");
}
public static void main(String[] args) {
describe(0);
describe(37);
describe(100);
}
}0.0 C = 32.0 F
37.0 C = 98.6 F
100.0 C = 212.0 FFor a fixed number of decimal places in the output, use System.out.printf("%.1f%n", value) or String.format.
Practice exercise
Write boolean isPrime(int n) and print every prime from 1 to 30 on one line.
Show solution
public class PrimeList {
static boolean isPrime(int n) {
if (n < 2) return false;
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) return false;
}
return true;
}
public static void main(String[] args) {
StringBuilder primes = new StringBuilder();
for (int i = 1; i <= 30; i++) {
if (isPrime(i)) primes.append(i).append(' ');
}
System.out.println(primes.toString().trim());
}
}2 3 5 7 11 13 17 19 23 29Key takeaway#
Finished this lesson?