Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning values to static final variables

Tags:

java

static

public class A{
    public static final int j;
    public static int x; 
    static{ 
         j=9; 
    }
    public A(int j)
    {
         j = j;
    }
    protected void print()
    {
           System.out.println(j);
    }
}

When trying code above in the eclipse, eclipse shows that "The assignment to variable j has no effect" is shown for intializing the vaiable "j" in the constructor.

Please do tell me why the variable j has no effect.

like image 237
chaitu Avatar asked Dec 12 '22 02:12

chaitu


2 Answers

The parameter j is shadowing the class member j. Try to change your code as follows:

public A(int j)
{
     A.j = j;
}
like image 131
michael667 Avatar answered Feb 07 '23 07:02

michael667


The class variable j (static final int j) is assigned the value 9 in the static block. That is all valid.

In the constructor, the parameter j, is assigned to itself and that has no effect. The alternative (and I suspect what you meant) is:

public A(int j)
{
     A.j = j;
}

Here the parameter j is assigned to the class variable j. However, Java will complain here as the class variable is final. If you remove the final keyword, this will of course work as well. However, now it gets interesting:

The value of class j, will be 9 as long as no instance of class A is created. The moment an instance of the class is created through the new operator, all instances of the class A will have the same value for the class variable j (dependant on what you sent the constructor).

like image 36
Jaco Van Niekerk Avatar answered Feb 07 '23 06:02

Jaco Van Niekerk