Java – Static Variables

Static Variable:

  • Defining a variable inside the class and outside to methods.
  • Static variable must define with static keyword.
  • Static Variable access using Class-Name.
class Bank
{
      static String bankName = “AXIS”;
}

Note: We always process the data (perform operations on variables) using methods.

Getter and Setter Methods:

  • set() method is used to set the value to variable.
  • get() method is used to get the value of variable.
  • Static variables : process using static set() and get() methods
  • Instance variables : process using instance set() and get() methods
class Code
{
            static int a;
            static void setA(int a){
                        Code.a = a;
            }
            static int getA(){
                        return Code.a;
            }
            public static void main(String[] args){
                        Code.setA(10);
                        System.out.println(“A val : ” + Code.getA());
            }
}

Static variables automatically initialized with default values based on datatypes:

DatatypeDefault Value
int0
double0.0
charBlank
booleanfalse
Stringnull
class Code
{
            static int a;
            static double b;
            static char c;
            static boolean d;
            static String e;
            public static void main(String[] args)
            {
                        Code.values();
            }
            static void values()
            {
                        System.out.println(“Default values : “);
                        System.out.println(“int : ” + Code.a);
                        System.out.println(“double : ” + Code.b);
                        System.out.println(“char : ” + Code.c);
                        System.out.println(“boolean : ” + Code.d);
                        System.out.println(“String : ” + Code.e);
            }
}

It is recommended to define get() and set() method to each variable in the class:

class First
{
            static int a, b, c;
            static void setA(int a){
                        First.a = a;
            }
            static void setB(int b){
                        First.b = b;
            }
            static void setC(int c){
                        First.c = c;
            }
            static int getA(){
                        return First.a;
            }
            static int getB(){
                        return First.b;
            }
            static int getC(){
                        return First.c;
            }
}
class Second
{
            public static void main(String[] args)
            {
                        First.setA(10);
                        First.setB(20);
                        First.setC(30);
                        System.out.println(“A val : ” + First.getA());
                        System.out.println(“B val : ” + First.getB());
                        System.out.println(“C val : ” + First.getC());
            }
}
Scroll to Top