Static Function in JavaIn 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 FunctionIf 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
Declaring a Static FunctionThe 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: 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 FunctionIn 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 JavaLet'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 MethodThere are two main restrictions for the static method. They are:
Demo.java Output: Next TopicUnary Operators in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India