Static Methods in Java
A static method in a class is a method declared with the static modifier. The following is a class Helper defined with static methods abs() and main():
public class Helper { public static int abs(int num) { return (num < 0) ? (-num) : num; } public static void main(String[]args) { System.out.println(abs(5)); } }
The signature of the method abs() is:
public static int abs(int num)
It has the following parts:
- public: access modifier, which indicates the method is accessible outside of this class.
- static: modifier, which indicates this is a static method.
- int: the type of the return value. The return type could be void, which means no returns.
- abs: the method name
- (int num): the parameter list. Here there is only one parameter num of type int.
The method body is enclosed with brackets {}; it contains the code to be executed when the method is called. If the return type is not void, we have to have a return statement in every branch of control flow.
The main() method is also a static method, with no returns but with an array of strings as the parameter.
Static methods can not directly call a non-static method within the same class, since a non-static method needs instantiating an object. To access a static method in another class, we can directly use the class name followed by the method name. For example,
Helper.abs(-3);
Static methods are often used in code libraries. For example,
Integer.parseInt("123"); // Convert string to integer Double.parseDouble("1.23"); // Convert string to double Math.sqrt(123); // Compute the square root Math.random(); // Generate a random number
Related documents:
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#parseDouble(java.lang.String)
http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html