Methods. 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.
Static example. This program has 2 static methods. The methods are static because they do not require an object instance. The 2 methods compute lengths.
Start We see how to directly call a method. We call the totalLength method from main.
Note With averageLength(), we call another method. This shows methods can call methods.
Note 2 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
Overload. 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.
So We do not need to remember a different name for "action" in this program. Each call is inferred by its arguments—an 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
Instance methods. 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.
Tip Methods are by default instance and private. We make the method here public, but leave it as an instance method.
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
Public, private. 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
Protected. A method that is protected is accessible to any child classes. So if a class extends another, it can access protected methods in it.
Note The default accessibility also allows this. But protected makes this concept explicit.
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
Return. 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
Void. 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 method. A 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.
Here We instantiate a Cat object. We then call its isFuzzy boolean method, which always returns true.
Important This design can be useful in real programs. For example, some Cats might be hairless—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
Variable argument lists. 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
Interface methods. A method can be invoked through an interface reference. This often incurs a performance cost. But it can help unify a program's construction.
Summary. We use methods throughout software. We prefer instance methods where appropriate. Static methods too are often useful. With methods we construct reusable logic pieces.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 29, 2023 (simplify).