1. Home
  2. Interview Questions
  3. Java
  4. How do final variables differ from static final variables?

How do final variables differ from static final variables?

☕ Java Hard 🎓 Experienced 💬 1 answer 📅
WhatsApp Telegram LinkedIn X

Try answering first

In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.

1 Answer

0 0
InterviewQuestions Team ✔ Expert answer ✔ Best answer ·

Short answer: Final variables cannot change their value after being initialized, while static final variables belong to the class and are shared among instances.

Detailed explanation

In Java, the final keyword is used to declare constants. A final variable can be assigned a value only once; if you try to assign it again, the compiler will throw an error. Final variables can be instance variables, which means that each instance of the class maintains its copy of the variable, or they can be static variables.

On the other hand, static final variables are constants shared across all instances of a class. They are typically defined on the class itself and are initialized at the time of declaration or within a static block. They provide a way to represent fixed values that should be accessible across various instances of a class without being duplicated.

Example

public class Example {
    final int instanceVar = 10;
    static final int STATIC_VAR = 20;

    public static void main(String[] args) {
        Example ex1 = new Example();
        Example ex2 = new Example();
        System.out.println(ex1.instanceVar); // 10
        System.out.println(Example.STATIC_VAR); // 20
    }
}

Common mistakes

  • Forgetting that final instance variables need to be initialized in the constructor.
  • Trying to reassign a final variable after it has been initialized.
  • Assuming static final variables can be different for each instance of a class.

Follow-up questions

  • Can a final variable be initialized in a method?
  • What happens if a static final variable is not explicitly initialized?
  • How does final work with method overriding?

Interview tip: Be clear about the scope and lifetime implications of final variables in your explanations.

Reviewed by the Interview Questions editorial team · Last updated

How well did you know this?

Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.

Your Answer

More hard Java questions

All hard questions →

Related Questions

‹
Q7 of 18 · Java
Next ›

Interview Questions

Free interview questions and answers, MCQ practice, online tests, mock interviews and group discussions — everything you need to crack your next interview.
📍 Dasardot LLC
1309 Coffeen Avenue STE 1200
Sheridan, Wyoming 82801
USA