In Java, the static keyword can be used with variable, constant, and functions. The main purpose of using the static keyword is to manage the memory so that we can use the memory efficiently. In this section, we will discuss the static function in Java.
Static Function
If the keyword static is prefixed before the function name, the function is called a static function. It is often called a method.
A method is a group of variables and statements that functions together as a logical unit. Like fields, methods can have modifiers (like private, public, or static). Methods also have a return type (may be void if the method returns nothing). The return type can be a reference type (such as an object or an array). A method can have any number of parameters or arguments.
When a function is static, it is really part of the class and not part of the individual objects in the class. It means that static functions exist even before creating any objects.
The best example of a static method is the main() method.
Properties of Static Function
- It can access only static members.
- It can be called without an instance.
- It is not associated with the object.
- Non-static data members cannot be accessed by the static function.
Declaring a Static Function
The declaration of a static function in Java is the same as the declaration of a method. The function has two parts function prototype and body of the function.
The function prototype contains the function signature that includes the function name, return type, access specifier, and the parameters list. The function body contains the logic or functionality to be performed.
Syntax:
- [access specifier] static [return type] [function name] (parameter list)
- {
- //body of the function
- }
In the above syntax, the access specifier and the parameter list are optional. A function may or may not have a parameter list. For example:
- public static int sum(int a, int b)
- {
- int c=a+b;
- return c;
- }
Calling Static Function
In Java, we cannot call the static function by using the object. It is invoked by using the class name.
- [class name].[method name]
For example:
- Math.sqrt(a); //calling the square root function of the Math class