Java Static Keyword

This Java article uses static fields and static methods. A static member is tied to a type, not an instance of the type.
Static. In stasis, a thing exists, but in only one place, at one time. It is singular. A static variable is tied to no class instance. It occupies one location in memory.
Similarly, static methods act on no instance data. They operate on static data. They are often entry points. But we can create (or access) instances of classes inside them.Class
Field, method. This program has two static things. It has a static field, named count, that is of type int. Second it has the main() entry point, which is where control flow begins.

Tip: Main can access the count field because the field is static. It uses the static keyword.

And: A static field can be accessed by both static and instance methods. An instance field, however, cannot be accessed by static methods.

Java program that uses static variable public class Program { static int count; public static void main(String[] args) { // Increment static variable. Program.count++; System.out.println(Program.count); // Repeat the increment. // ... The memory was not erased. Program.count++; System.out.println(Program.count); } } Output 1 2
Memory locations. A static field denotes a single memory location. When we increment count, its value is stored in that location. Its value then is not reset or erased when used again.

Note: We use the System.out.println method to write the count value to the console.

Console
Instances versus static. Consider this program. It has a static int and a non-static int in the Program class. We access the static "size" with Program.size.

But: To access the instance field "code," we must first create an instance of the Program class. It is tied to an instance, not the type.

Java program that uses instances, static public class Program { static int size = 100; int code = 1000; public static void main(String[] args) { // Access static field with type name. System.out.println(Program.size); // Access instance field with instance. Program p = new Program(); System.out.println(p.code); } } Output 100 1000
Final versus static. A final field cannot be changed in a program. A static field, existing in only one place, can be changed. If you try to change a final field, a compiler error occurs.Final

Final: This means "constant." A local variable may be declared final: it is a constant local.

Static: This means "in one place." Locals may not be static—we can use static fields and methods.

Java program that uses final, static public class Program { static int _id = 5; final int _code = 100; public static void main(String[] args) { _id++; // This is valid. _code++; // This fails. } } Output Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot make a static reference to the non-static field _code
Static method performance. Compilers implement instance methods with an invisible first argument: the instance itself. I timed an instance method (getNumber) and a static one (getNumber2).

Note: I used nested loops to call the methods, making the benchmark times longer and more reliable.

Result: The static method calls were faster. They do not require the instance, so are simpler and faster.

Java program that times static method public class Program { int getNumber(int a) { // An instance method. return a * 2; } static int getNumber2(int a) { // A static method. return a * 2; } public static void main(String[] args) throws Exception { Program p = new Program(); long t1 = System.currentTimeMillis(); // ... Call instance method. for (int x = 0; x < 100; x++) { for (int i = 0; i < 10000000; i++) { if (p.getNumber(i) < 0) { throw new Exception(); } } } long t2 = System.currentTimeMillis(); // ... Call static method. for (int x = 0; x < 100; x++) { for (int i = 0; i < 10000000; i++) { if (Program.getNumber2(i) < 0) { throw new Exception(); } } } long t3 = System.currentTimeMillis(); // ... Times. System.out.println(t2 - t1); System.out.println(t3 - t2); } } Output 955 ms, int getNumber() [Instance] 880 ms, static int getNumber2() [Static]
Instance arguments. To a compiler, instance methods are often static ones with a hidden first argument—the instance reference. Static methods can receive class arguments.

So: The key difference between a static and instance method is clarity of syntax. It is easier to decide what an instance method does.

Thus: Object-oriented programming is about clarity and maintainability. It makes complex programs easier for regular people to build.

Static field performance. In my test, a static field is slower to access than an instance (class-based) field. The time increase is consistently measurable.

So: Any speed gains from using static methods may easily be erased by excessive static field accesses.

Java program that benchmarks static fields public class Program { int field1 = 100; static int field2 = 100; public static void main(String[] args) throws Exception { Program p = new Program(); long t1 = System.currentTimeMillis(); // ... Use instance field. for (int x = 0; x < 100; x++) { for (int i = 0; i < 10000000; i++) { if (p.field1 * 2 <= 199) { throw new Exception(); } } } long t2 = System.currentTimeMillis(); // ... Use static field. for (int x = 0; x < 100; x++) { for (int i = 0; i < 10000000; i++) { if (Program.field2 * 2 <= 199) { throw new Exception(); } } } long t3 = System.currentTimeMillis(); // ... Times. System.out.println(t2 - t1); System.out.println(t3 - t2); } } Output 763 ms, field1 [Instance field] 953 ms, field2 [Static field]
A balance. We achieve speed increases with static methods. But if those methods use excessive static fields, we lose our optimization. A delicate balance is needed for optimal speed.
A review. Static methods and fields are used throughout Java programs. The main() method, used in every program, is itself a static method.
No instances. No class instance is required to invoke main. Static fields are similar—they require no instances. They are often used as global variables.
In program design, correctness is most important. Other considerations, like static versus non-static, are second to correctness. Performance matters little when a program fails.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
HomeSearch
Home
Dot Net Perls