Saturday, March 26, 2016

static final vs final

We know that static final are used to define constants and a static to define class level members. But
how and when they are loaded?

Lets take an example

class Test{

static final int x=10;
static int y=20;

public static void main(String []args){
    int var1=x;
    int var2=y;

}
}

compile it, and decompile the .class file
you will see something like this

class Test
{
  static final int x = 10;
  static int y = 20;
 
  public static void main(String[] paramArrayOfString)
  {
    int i = 10;  ----> the static final varible is loaded and used in compile time itself
    int j = y;
  }
}

java compiler does some kind of optimization and since a constant(static final) will not be changed, it assigns it in compile time itself

No comments:

Post a Comment