Answer: – The methods that are declared with keyword static called static methods. Since these static methods are offend referred to as class method in order to distinguish them from there counterpart, instance method. Since method are used when we want to have a variable common to all instance of a class. One of the most common example is to have a variable that could keep a count of how many objects of a class have been created. Remember, java creates only one copy for a static method which can be used even if the class is never actually initiated.

Like static variables, static methods can be called without using the object. They are also available for use by other classes. Methods that are of general utility but do not directly affects an instance of that class are usually declared as class method. Java class library. Contains a large number of class method. For example, math class of java library defines many static methods to perform math operation that can be used in any program. An example of static method is –

class MathOperation
{
                static float multiply(float x,float y)
                {
                                return x*y;
                }
                static float divide(float x,float y)
                {
                                return x/y;
                }
}
class MathApplication
{
                public static void main(String args[])
                {
                                float a=MathOperation.multiply(4.0f,5.0f);
                                float b=MathOperation.divide(a,2.0f);
                                System.out.println("B = "+b);
                }
}

An example of static method is –.PNG

In the above program, two classes namely math operation and math application is used. The math operation is an external class and math application is a main method class. The main method class call external class method without declaration of any object because these methods are declared as static method.

The main method class of java is similar like main() function of C and C++. At least one class must be use in a java program and this class is called main method class actually programs of java compile only when main method class is used in the program. Name of the java program must be main method class name. A main method class can be declared similar as other classes but it contains main method with the following syntax –

                public static void main(String args[])

Inside this method, actual program can be executed. With help of this method, objects of other classes as well as variables of same class can be use perform operation of the main method class.

Advertisements