Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static variable initialization java

how to initialize a private static member of a class in java.

trying the following:

public class A {    private static B b = null;    public A() {        if (b == null)          b = new B();    }     void f1() {          b.func();    } } 

but on creating a second object of the class A and then calling f1(), i get a null pointer exception.

like image 744
Rohit Banga Avatar asked Oct 29 '09 08:10

Rohit Banga


People also ask

How do you initialize a static variable in Java?

The only way to initialize static final variables other than the declaration statement is Static block. A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.

Can static variables be re initialized in Java?

Declaring variables only as static can lead to change in their values by one or more instances of a class in which it is declared. Declaring them as static final will help you to create a CONSTANT. Only one copy of variable exists which can't be reinitialize.

How do you initialize a static variable?

As static variables are initialized only once and are shared by all objects of a class, the static variables are never initialized by a constructor. Instead, the static variable should be explicitly initialized outside the class only once using the scope resolution operator (::).

Can we initialize the static variable?

A static variable in a block is initialized only one time, prior to program execution, whereas an auto variable that has an initializer is initialized every time it comes into existence. A static object of class type will use the default constructor if you do not initialize it.


2 Answers

The preferred ways to initialize static members are either (as mentioned before)

private static final B a = new B(); // consider making it final too 

or for more complex initialization code you could use a static initializer block:

private static final B a;  static {   a = new B(); } 
like image 115
sfussenegger Avatar answered Oct 03 '22 09:10

sfussenegger


Your code should work. Are you sure you are posting your exact code?


You could also initialize it more directly :

    public class A {        private static B b = new B();        A() {       }        void f1() {         b.func();       }     } 
like image 41
KLE Avatar answered Oct 03 '22 08:10

KLE