×
☰ See All Chapters

static keyword in Java

static is a non-access specifier can be used with members of a class except with constructor. static members are also known as Class members.  static members should be declared with the static keyword just inside a class, but outside a method, constructor or a block. A method can be static, a block can be static but blocks, variable inside any method cannot be static. Static members should be declared inside class but outside the block.

static-keyword-in-java-0
 

There would only be one copy of each static member per class, regardless of number of objects created from it.

class Counter {

        static int count;

        void counting() {

                ++count;

                System.out.println(count);

        }

}

 

class CounterDemo {

        public static void main(String[] args) {

                Counter.count = 0;// Access with class name

                Counter c1 = new Counter();

                c1.counting();

                Counter c2 = new Counter();

                c2.counting();

        }

}

 

     Output

1

2

Static member are stored in static memory.  Static member are created when the program starts and destroyed when the program stops. Visibility is similar to instance member. However, most static members are declared public since they must be available for users of the class. Static variable have same default values instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null.  For static variables values can be assigned during the declaration or within the constructor or in other classes or in methods. Additionally values can be assigned in special static initializer blocks. Declaration and initialization of static variables cannot be done separately as below:

static int num;

num = 100;

 

If static variables are declared final, then they must be initialized while declaring. For outside the class, Static member can be accessed by calling with the class name as

className.memberName

For inside the class, Static member can be accessed with their name itself. When declaring static variables as public static final, then variables names (constants) are all in upper case. If the static variables are not public and final the naming syntax is the same as instance and local variables.

 

static-keyword-in-java-1
 

Accessing static variables outside the class

 

package com.java4coding;

 

public class Demo {

        public static void main(String[] args) {

                Counter.count = 0;// Access with class name

                Counter.counting();

                Counter.counting();

        }

}

 

class Counter {

        static int count;

        static void counting() {

                ++count;

                System.out.println(count);

        }

}

Output:

1

2

 

 


All Chapters
Author