Javatpoint Logo
Javatpoint Logo

Static Function in Java

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.

Static Function in Java

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:

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:

Calling Static Function

In Java, we cannot call the static function by using the object. It is invoked by using the class name.

For example:

Example of Static Function in Java

Let's create a Java program from which we can clearly understand the difference between static and non-static functions.

StatciFunctionExample.java

Output:

A non-static function is called.
The static function is called.

Let's create a Java program and call a static method from another static method even without creating an object of the class.

CalculateCube.java

Output:

Cube of 7 is: 343

Restrictions of the Static Method

There are two main restrictions for the static method. They are:

  • The static method cannot use non-static data members or call a non-static method directly.
  • this and super keyword cannot be used with a static context.

Demo.java

Output:

Static Function in Java




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA