Mike K.

asked • 01/25/19

What does 'static' mean in Java?

1 Expert Answer

By:

Thomas L.

Awesome illustration, thank you. I have a better understanding of the concept.
Report

07/31/19

Bob P.

tutor
I'm glad that helped. A recent student was comfortable with the distinction between instance variables and static variables, but was not comfortable with the distinction between instance variables and static methods. A Java class (think "classification") defines what a particular type of thing looks like and acts like. It is in some ways similar to a "factory" which holds the blueprints for, and produces instances of (via a constructor when called with "new"), a certain type of thing. As mentioned previously above, the class is like the metal cookie cutter, which determines the shape, while the instances are like the individual cookies which are stamped out using that metal cookie cutter. 1a) Instance variables and/or instance methods live in the instances which are produced by calling the constructor. The cookies are instances. 1b) Static variables and/or methods live in the class definition itself (the cookie cutter). 2a) If you need to use an instance variable in a method, then the method MUST be an instance method. The compiler will prevent you from compiling if you try to have a static method which tries to access an instance variable. 2b) If you only need to use input parameters and/or static variables in a method, and there is absolutely no dependency on any instance variables, then the method can be a static method. The compiler won't stop you from making such a method an instance method, but if the method doesn't need to access any instance variables, then there is no need to have a copy of that method in each and every instance... it's better to have the method be static, and there will be only a single copy of that method in the class definition itself (the cookie cutter), rather than a copy of the code for that method in each and every instance (cookie). 3a) Instance methods are accessed via an object reference to a particular instance. For example: String s1 = "Hello"; String s2 = "cat"; int length1 = s1.length(); int length2 = s2.length(); // length1 is now 5, and length2 is now 3 3b) Static methods (a.k.a. "Class methods") are accessed via the class name itself. For example: int x = 1234; String s = String.valueOf(x); // s is now "1234" (as a String, rather than as a primitive int).
Report

12/28/21

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.