Java Articles

Static methods and variables

A static member is defined for the class itself and exists independently of any object of that class.

Static method

A static method is associated with a class. Therefore, it is not necessary to create an instance of that class in order to invoke such a method.

Syntax of Static method

static retType funcName(ParamList)

{

// Body of this method

}

Syntax to call Static method

className.funcName(arguments);

Where className is a name of the class and funcName is the name of the static method. Math class provides several examples of static methods. For examples,

static float abs(float f)

static int abs(int i)

static int min(int i, int j)

static int max(int i, int j)

Static variable

Static variable is also associated with a class. It is not necessary to create an instance of that class in order to read or write such a variable. Since static variable is associated with a class, there is only one copy of the variable and it is shared by all objects of that class.

Syntax of static variable

className.varName

Where className is a name of the class and varName is a name of the static variable. Math class provides 2 static variables i.e. E and PI.