I’m always confused between static and final keywords in java.
How are they different ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The static keyword can be used in 4 scenarios
Let’s look at static variables and static methods first.
Static variable
Class.variableStatic method
Class.methodName()thisorsuperkeywords in anyway.Static class
Java also has "static nested classes". A static nested class is just one which doesn’t implicitly have a reference to an instance of the outer class.
Static nested classes can have instance methods and static methods.
There’s no such thing as a top-level static class in Java.
Side note:
finalkeyword is used in several different contexts to define an entity which cannot later be changed.A
finalclass cannot be subclassed. This is done for reasons of security and efficiency. Accordingly, many of the Java standard library classes arefinal, for examplejava.lang.Systemandjava.lang.String. All methods in afinalclass are implicitlyfinal.A
finalmethod can’t be overridden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.A
finalvariable can only be initialized once, either via an initializer or an assignment statement.It does not need to be initialized at the point of declaration, this is called a
blank finalvariable, but in this case:blank finalinstance variable must be assigned at every constructor of its class.blank finalstatic variable must be assigned in a static initializer in its class.Note: If the variable is a reference, this means that the variable cannot be re-bound to reference another object. But the object that it references is still mutable, if it was originally mutable.
When an anonymous inner class is defined within the body of a method, all variables declared
finalin the scope of that method are accessible from within the inner class. Once it has been assigned, the value of the final variable cannot change.