With methods, we condense and simplify program logic. This makes Java programs more versatile—easier to modify and understand.
With overloaded methods, we can make programs clearer and faster. Methods can return a value, or no value (if they are void
). Inside classes, programs contain many methods.
This program has 2 static
methods. The methods are static
because they do not require an object instance. The 2 methods compute lengths.
totalLength
method from main.averageLength()
, we call another method. This shows methods can call methods.AverageLength
depends on totalLength
. Suppose totalLength()
is changed. AverageLength()
will automatically implement this change.public class Program { static int totalLength(String a, String b) { // Add up lengths of two strings. return a.length() + b.length(); } static int averageLength(String a, String b) { // Divide total length by 2. return totalLength(a, b) / 2; } public static void main(String[] args) { // Call methods. int total = totalLength("Golden", "Bowl"); int average = averageLength("Golden", "Bowl"); System.out.println(total); System.out.println(average); } }10 5
A method can have one name, but many argument lists, many implementations. This is called overloading. Each method is separate, but the name is shared.
int
, a String
.public class Program { public static void action(int value) { System.out.println("Int = " + Integer.toString(value)); } public static void action(String value) { System.out.println("Length = " + value.length()); } public static void main(String[] args) { // Call with Integer argument. action(1); // Call with String argument. action("cat"); } }Int = 1 Length = 3
These are accessed through an instance of a class
, not the class
type itself. So if we have a size()
method on an Item, we must first create an instance of the Item class
.
class Item { public int size() { return 10; } } public class Program { public static void main(String[] args) { // The size method can only be accessed from an instance. Item item = new Item(); int value = item.size(); System.out.println(value); } }10
A method can specify how accessible it is to other parts of the program. A public method is accessible everywhere. A private method can only be called from the same class
.
class Test { public void apply() { System.out.println("Apply called"); this.validate(); } private void validate() { System.out.println("Validate called"); } } public class Program { public static void main(String[] args) { // Create new Test and call public method. Test t = new Test(); t.apply(); // Cannot call a private method: // t.validate(); } }Apply called Validate called
A method that is protected is accessible to any child classes. So if a class
extends another, it can access protected methods in it.
class Widget { protected void display() { System.out.println(true); } } class SubWidget extends Widget { public void use() { // A subclass can use a protected method in the base class. // ... It cannot use a private one. super.display(); } } public class Program { public static void main(String[] args) { SubWidget sub = new SubWidget(); sub.use(); } }true
In non-void
methods, a return value must be supplied. This must match the declaration of the method. So the getName
method here must return a String
.
public class Program { static String getName() { // This method must return a String. return "Augusta"; } public static void main(String[] args) { String name = getName(); System.out.println(name); } }Augusta
This term means "no return value." So a void
method returns no value—it can use an empty return statement. An implicit return is added at the end.
public class Program { static void test(int value) { if (value == 0) { // A void method has no return value. // ... We use an empty return statement. return; } System.out.println(value); // A return statement is automatically added here. } public static void main(String[] args) { // No variables can be assigned to a void method call. test(0); // No effect. test(1); } }1
Boolean
methodA boolean (or predicate) method returns true or false. In classes, we often have public boolean methods (like isFuzzy
here) that reveal information about a class
's state.
isFuzzy
boolean method, which always returns true.isFuzzy
would return false.class Cat { public boolean isFuzzy() { return true; } } public class Program { public static void main(String[] args) { Cat c = new Cat(); // Call boolean instance method. if (c.isFuzzy()) { System.out.println(true); } } }true
A method can receive an array of arguments of any length. These array elements can be passed directly at the call site.
public class Program { static void displayAll(int... test) { // The argument is an int array. for (int value : test) { System.out.println(value); } System.out.println("DONE"); } public static void main(String[] args) { // Pass variable argument lists to displayAll method. displayAll(10, 20, 30); displayAll(0); displayAll(); } }10 20 30 DONE 0 DONE DONE
A method can be invoked through an interface
reference. This often incurs a performance cost. But it can help unify a program's construction.
Optional
With this class
, we can call methods with optional arguments. Some extra code complexity is required, but we can avoid using invalid values.
We use methods throughout software. We prefer instance methods where appropriate. Static methods too are often useful. With methods we construct reusable logic pieces.