Home
Search
Java Method ExamplesUse instance and static methods. Review overloaded method syntax.
dot net perls
Methods. With methods, we condense and simplify program logic. This makes Java programs more versatile—easier to modify and understand.
Static. This program has two static methods. The methods are static because they do not require an object instance. The two methods compute lengths.
Static
TotalLength We see how to directly call a method. We call the totalLength method from main.
AverageLength With averageLength(), we call another method. This shows methods can call methods.
Info AverageLength depends on totalLength. Suppose totalLength() is changed. AverageLength() will automatically implement this change.
Java program that introduces methods
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.
Overload
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.
Java program that overloads methods
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.
Java program that calls instance method
class Item { public int size() { // An instance method. 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.
Public Many classes require entry points other than the constructor. A public method, like apply() here, is an entry point.
Private Classes contain internal, class-only implementation logic. Private methods work well for this purpose.
Default The default is package-based. So when you don't specify public or private, the method can be used throughout the entire package.
Java program that uses public, private methods
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.
Java program that uses protected method
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.
Return
Java program that uses return statement
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.
Java program that has void method
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.
Java program that uses boolean method
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.
Varargs In older languages like C, this syntax was called varargs. In C# we use the params keyword.
Ellipsis The ellipsis (three dots) indicates a variable-length array of the type. So the displayAll method receives an int array.
Java program that uses variable argument list syntax
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.
Interfaces
Optional. With this class, we can call methods with optional arguments. Some extra code complexity is required, but we can avoid using invalid values.
Optional
Lambda. The Java language supports lambda expressions. With a lambda, we specify with concise syntax a function object. These help with smaller tasks.
Lambda
A 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.
Home
© 2007-2021 sam allen. send bug reports to info@dotnetperls.com.