What is difference between static method and static
variable?

Answer Posted / joh-b tanzania

The static keyword denotes that a member variable, or method, can be accessed without requiring an instantiation of the class to which it belongs.

In simple terms, it means that you can call a method, even if you've never created the object to which it belongs! Every time you run a stand-alone application (which requires a static main method), the virtual machine can call the main method without creating a new application object. Of course, unless the application's methods are all static, you will need to create an instance of it at some point.

With regard to member variables, it means that they can be read from, and written to, without creating an object. You may have noticed that many classes create constants that can be read, without creating an object.

static final int VERSION = 2;

Static member variables are shared by all instances of the class to which they belong. When writing classes, this can be a handy feature. Consider the following example, where a counter is used to track how many myObject instantiations have taken place.

public class myObject
{
static int objectCount = 0;

public myObject()
{
objectCount++;
}

public String toString()
{
return new String ("There are " + objectCount + " objects");
}
}

Is This Answer Correct ?    3 Yes 1 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

How do listeners work?

751


What is java’s garbage collected heap?

727


In the below example, what will be the output?

802


Can we have multiple public classes in a java source file?

786


How the metacharacters are different from the ordinary characters?

779


Is it possible for a yielded thread to get chance for its execution again?

731


Why wait and notify methods are declared in object class?

800


Is java an open source?

733


who can i handle multiple client in RMI

1662


How do you override a private method in java?

699


What is static data type in java?

774


How do I remove a character from a string in java?

719


What are the advantages and disadvantages of reference counting in garbage collection?

782


What do you understand by java virtual machine?

926


Explain covariant method overriding in java.

787