A class can be immutable in Android

Static variables, constants and methods in Java

In this post we cover static variables, constants, and methods.

In Java, with the help of static program elements, properties can be used that are not tied to instances (concrete objects) of a class.

At the end of the article we introduce the static initializer, which can be used to carry out more complex initializations.

With the static initializer, static variables and constants in Java can also be initialized at any point in the class definition after they have been declared.

Static variables (class variables) and constants in Java

Static variables exist independently of an object. In contrast to object variables, they are called via the class and not via a specific object.

If you want to define a static variable in Java, you have to use the keyword static declare as static, e.g. like this:.

This static variable is accessed via the class in which it is defined, namely via the class name:.

In Java, each static variable is created only once and can be called from all objects of this class. Since all instances of a class share the class variables, changes made to the static variables by one instance also affect all other instances.

Therefore, class variables can be viewed as global variables that exist from the time their classes were loaded until the end of the program. Since every static variable is called using the name of its class, no name collisions can occur.

Static constants in Java

If you want to define a static variable as a constant, you have to use the keyword final declared as immutable, something like this:.

By the keyword final the class variable can no longer be changed after initialization. It cannot be assigned a new value in the further course of the program. For better readability, constant names are capitalized in Java.

In the following example application we will use a static variable and with its help count the number of currently existing instances of its own class. A static constant is also defined in the application.

/ * * Example application for static variables and constants in Java * / public class TestObjekt {private static int anzObj; private static final int MAXOBJ = 5; // constant must be at Initial. set // private static final int MINOBJ; // no value set, therefore compiler error public TestObject () {this.anzObj ++; // this pointer in constructors to class variables allows System.out.println ("Object created!"); } public void finalize () {this.anzObj--; // this pointer allowed in non-static methods System.out.println ("Object deleted!"); } public static void main (String [] args) {// this.anzObj = 0; // this pointer does not exist in static methods TestObject.anzObj = 0; // numObj = 0; can also be used TestObject obj1 = new TestObject (); TestObject obj2 = new TestObject (); TestObject obj3 = new TestObject (); obj1.finalize (); System.out.println ("\ nObjects:" + TestObject.anzObj + "\ n"); for (int i = TestObject.anzObj; i In Line 7 becomes the static variable numobj Are defined. The class variable is not yet assigned a value when it is declared; this is only done in Line 26 with access via the class name:.

In Line 8 becomes the static constant MAXOBJ declared and initialized with the value 5. In Line 36 the value of the constant is queried; here, too, access is via the class name:.

The statement in Line 25 is commented out. She would become one CompilerErrors because the this- Pointer is not available in static methods. Instead, static variables and constants must be accessed using the class name, as in Line 26.

Now let's start the sample application. The resulting text output is shown in the command line output shown below:

Java static variables and constants - output of the sample application

Static methods (class methods) in Java

Another static program element in Java are class methods. Class methods are static methods and exist independently of a specific instance.

A static method is called via the class in which it is defined and the call is made via the name of the class:.

Methods are implemented in Java with the help of the staticKeyword declared as static. The following declaration defines a static method the one int-Value returns:.

Note: Instance variables cannot be accessed from class methods, since static methods exist independently of specific objects. In class methods, the this- Pointers not used. If it is used anyway, the developer receives a compiler error, as in Line 25 in the sample application above.

But it is also without this- Pointer possible to access static variables from static methods. To do this, the class name must be placed in front of the variable name. This prefixing of the class name (qualification by means of class name) is only necessary if the static variable is covered by a local variable.

The use of class methods is useful for calculations with primitive data types or if functions are to be made available that do not work with object data. Examples are in the Math- and system-Class can be found in the Java class library.

The best known static method in Java is the method Mainwhich serves as the starting point for any Java application.

The class methods: public static void main (String [] args)

The MainMethod is the entry point into Java applications. When starting a Java application, the Java interpreter loads the class object specified in the call and looks for a static method with the following signature: public static void main (String [] args).

Can the Java interpreter handle the MainMethod cannot be found, this leads to a runtime error and an error message is output.

Will the MainMethod is found, the Java interpreter creates an array with the command line parameters and passes the array as an argument to the Main-Method.

Multiple initialization using the static initializer

In Java, static variables can also be initialized after they have been declared. Often, however, the initialization takes place in one step with the declaration. However, this can quickly become confusing with more complex initializations. The static initializer solves exactly this problem and allows the subsequent initialization of static variables and constants.

The static initializer is similar to a constructor and allows any number of static variables and constants to be assigned start values, but a constant only once.

Multiple static initializers can be used in a class. They are defined as a block similar to a method and have the block name static. The static initializers are called when the class is loaded. Static variables and static initializers are executed in the textual order of their declaration.

In the following sample application, static variables and constants are initialized using static initializers.

/ * * Example application of the static initializers in Java * / public class StaticInit {private static int staticVar1, staticVar2, staticVar3; private static int staticVar4 = 0; private static final int CONSTANT1 = 5; // constant must be at Initial. private static final int KONSTANTE2, KONSTANTE3; // or from the static initializer static {staticVar1 = 2; staticVar2 = staticVar1 * 3; CONSTANT2 = 10; } public static void main (String [] args) {System.out.println ("\ nstaticVar1:" + staticVar1); System.out.println ("staticVar2:" + staticVar2); System.out.println ("staticVar3:" + staticVar3); System.out.println ("staticVar4:" + staticVar4); System.out.println ("\ nKONSTANTE1:" + KONSTANTE1); System.out.println ("KONSTANTE2:" + KONSTANTE2); System.out.println ("KONSTANTE3:" + KONSTANTE3); } static {staticVar1 = 4; staticVar3 = staticVar1 * staticVar2; staticVar4 = 50; CONSTANT3 = staticVar4; }}

In the Lines 12 to 17 and Lines 30 to 36 various static variables and constants are initialized with the help of two static initializers. It should be noted that static variables can be overwritten with values ​​several times, but constants can only be overwritten once.

Static initializers can also come at the end of the class definition, as in Lines 30 to 36. This is also the last possibility to initialize constants. If the declared constants have not been initialized by then, a compiler error occurs.

Now let's start the sample application. The resulting text output is shown in the command line output shown below:

Java Static Initializer - Sample application output

The following link will take you back to the Java programming course.