Class/Static Variables

  • Class variables otherwise called static variables are declared with the static keyword in a class, yet outside a constructor, method or scope.
  • There would just be one duplicate of each class variable for every class, paying little mind to what number of objects are made from it.
  • Static variables are seldom utilized other than being pronounced as constants. Constants are variables that are announced as private/public, static and final. Consistent variables never show signs of change from their introductory quality.
  • Static variables are put away in static memory. It is uncommon to utilize static variables other than announced final and utilized as either private or public constants.
  • Static variables are made when the system begins and annihilated when the execution stops.
  • Visibility is like instance variables. In any case, most static variables are announced public since they must be accessible for clients of the class.
  • Default values for these variables are also same as instance variables. For numbers, the default value id typically 0. However, the same value for Booleans is false and for object reference is invalid. Values can be doled out amid the assertion or inside the constructor. Furthermore, values can be appointed in unique static initializer brackets.
  • Static variables can be gotten to by calling with the class name . Classname.variablename.
  • When announcing class variables as public static final, variables names (constants) must all be in upper case. Moreover, the static variables are not public and the naming convention is the same as local and instance variables.

Sample Implementation:

import java.io.*;

public class Employeerecord{

private static double empcompensation;

public static final String empdept = “HR “;

public static void main(string args[]){

empcomp = 7500;System.out.println(empdept+” Compensation: “+empcompensation);

}

The compilation and execution of this code shall create the accompanying result:
HR Compensation: 7500