[java] Difference between Static and final?

I'm always confused between static and final keywords in java.

How are they different ?

This question is related to java

The answer is


final -

1)When we apply "final" keyword to a variable,the value of that variable remains constant. (or) Once we declare a variable as final.the value of that variable cannot be changed.

2)It is useful when a variable value does not change during the life time of a program

static -

1)when we apply "static" keyword to a variable ,it means it belongs to class.
2)When we apply "static" keyword to a method,it means the method can be accessed without creating any instance of the class


static means it belongs to the class not an instance, this means that there is only one copy of that variable/method shared between all instances of a particular Class.

public class MyClass {
    public static int myVariable = 0; 
}

//Now in some other code creating two instances of MyClass
//and altering the variable will affect all instances

MyClass instance1 = new MyClass();
MyClass instance2 = new MyClass();

MyClass.myVariable = 5;  //This change is reflected in both instances

final is entirely unrelated, it is a way of defining a once only initialization. You can either initialize when defining the variable or within the constructor, nowhere else.

note A note on final methods and final classes, this is a way of explicitly stating that the method or class can not be overridden / extended respectively.

Extra Reading So on the topic of static, we were talking about the other uses it may have, it is sometimes used in static blocks. When using static variables it is sometimes necessary to set these variables up before using the class, but unfortunately you do not get a constructor. This is where the static keyword comes in.

public class MyClass {

    public static List<String> cars = new ArrayList<String>();

    static {
        cars.add("Ferrari");
        cars.add("Scoda");
    }

}

public class TestClass {

    public static void main(String args[]) {
        System.out.println(MyClass.cars.get(0));  //This will print Ferrari
    }
}

You must not get this confused with instance initializer blocks which are called before the constructor per instance.


Static and final have some big differences:

Static variables or classes will always be available from (pretty much) anywhere. Final is just a keyword that means a variable cannot be changed. So if had:

public class Test{    
   public final int first = 10;
   public static int second = 20;

   public Test(){
     second = second + 1
     first = first + 1;
   }
}

The program would run until it tried to change the "first" integer, which would cause an error. Outside of this class, you would only have access to the "first" variable if you had instantiated the class. This is in contrast to "second", which is available all the time.


Think of an object like a Speaker. If Speaker is a class, It will have different variables such as volume, treble, bass, color etc. You define all these fields while defining the Speaker class. For example, you declared the color field with a static modifier, that means you're telling the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated.

Declaring

static final String color = "Black"; 

will make sure that whenever this class is instantiated, the value of color field will be "Black" unless it is not changed.

public class Speaker {

static String color = "Black";

}

public class Sample {

public static void main(String args[]) {
    System.out.println(Speaker.color); //will provide output as "Black"
            Speaker.color = "white";
    System.out.println(Speaker.color);  //will provide output as "White"
}}

Note : Now once you change the color of the speaker as final this code wont execute, because final keyword makes sure that the value of the field never changes.

public class Speaker {

static final String color = "Black";

}

public class Sample {

public static void main(String args[]) {
    System.out.println(Speaker.color); //should provide output as "Black"
            Speaker.color = "white"; //Error because the value of color is fixed.  
    System.out.println(Speaker.color); //Code won't execute.
}}

You may copy/paste this code directly into your emulator and try.


Easy Difference,

Final : means that the Value of the variable is Final and it will not change anywhere. If you say that final x = 5 it means x can not be changed its value is final for everyone.

Static : means that it has only one object. lets suppose you have x = 5, in memory there is x = 5 and its present inside a class. if you create an object or instance of the class which means there a specific box that represents that class and its variables and methods. and if you create an other object or instance of that class it means there are two boxes of that same class which has different x inside them in the memory. and if you call both x in different positions and change their value then their value will be different. box 1 has x which has x =5 and box 2 has x = 6. but if you make the x static it means it can not be created again. you can create object of class but that object will not have different x in them. if x is static then box 1 and box 2 both will have the same x which has the value of 5. Yes i can change the value of static any where as its not final. so if i say box 1 has x and i change its value to x =5 and after that i make another box which is box2 and i change the value of box2 x to x=6. then as X is static both boxes has the same x. and both boxes will give the value of box as 6 because box2 overwrites the value of 5 to 6.

Both final and static are totally different. Final which is final can not be changed. static which will remain as one but can be changed.

"This is an example. remember static variable are always called by their class name. because they are only one for all of the objects of that class. so Class A has x =5, i can call and change it by A.x=6; "


I won't try to give a complete answer here. My recommendation would be to focus on understanding what each one of them does and then it should be cleare to see that their effects are completely different and why sometimes they are used together.

static is for members of a class (attributes and methods) and it has to be understood in contrast to instance (non static) members. I'd recommend reading "Understanding Instance and Class Members" in The Java Tutorials. I can also be used in static blocks but I would not worry about it for a start.

final has different meanings according if its applied to variables, methods, classes or some other cases. Here I like Wikipedia explanations better.


Static variable values can get changed although one copy of the variable traverse through the application, whereas Final Variable values can be initialized once and cannot be changed throughout the application.


The two really aren't similar. static fields are fields that do not belong to any particular instance of a class.

class C {
    public static int n = 42;
}

Here, the static field n isn't associated with any particular instance of C but with the entire class in general (which is why C.n can be used to access it). Can you still use an instance of C to access n? Yes - but it isn't considered particularly good practice.

final on the other hand indicates that a particular variable cannot change after it is initialized.

class C {
    public final int n = 42;
}

Here, n cannot be re-assigned because it is final. One other difference is that any variable can be declared final, while not every variable can be declared static.

Also, classes can be declared final which indicates that they cannot be extended:

final class C {}

class B extends C {}  // error!

Similarly, methods can be declared final to indicate that they cannot be overriden by an extending class:

class C {
    public final void foo() {}
}

class B extends C {
    public void foo() {}  // error!
}

static means there is only one copy of the variable in memory shared by all instances of the class.

The final keyword just means the value can't be changed. Without final, any object can change the value of the variable.


Static is something that any object in a class can call, that inherently belongs to an object type.

A variable can be final for an entire class, and that simply means it cannot be changed anymore. It can only be set once, and trying to set it again will result in an error being thrown. It is useful for a number of reasons, perhaps you want to declare a constant, that can't be changed.

Some example code:

class someClass
{
   public static int count=0;
   public final String mName;

   someClass(String name)
   {
     mname=name;
     count=count+1;
   }

  public static void main(String args[])
  {
    someClass obj1=new someClass("obj1");
    System.out.println("count="+count+" name="+obj1.mName);
    someClass obj2=new someClass("obj2");
    System.out.println("count="+count+" name="+obj2.mName);
  }
}

Wikipedia contains the complete list of java keywords.