0
class Temp{
       final static int x;
     public static void main(String[] args){
    }
}

Compilation error: variable x not initialized in the default constructor

Why it says not initialized in default constructor since the variable is static? What is the role of default constructor here?

2
  • 2
    That's because the variable is final, you need to initialize it at the moment of its declaration. Commented Jul 13, 2017 at 10:56
  • 2
    or in a static initializer block Commented Jul 13, 2017 at 10:57

2 Answers 2

3

You're right, that error message is not very helpful. A static final variable (the convention is generally to put static before final) must be initialised either at the declaration point or via a static block:

final static int x = 0;
//or
final static int y;
static {
  y = 0;
}

I can't say any related bug reports so you could submit one if you want.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanx... I tried for final non-static variable also... It gives the same error. In case of final non static... Error is acceptable
1

It is not only static... it is final static :) static final members should be initialized inline or in static block.

3 Comments

Thanx... But my question was that what is the role of default constructor here
@RahulGupta it is most definitely not the role of any constructor, default or otherwise, to initialize static fields, and on that point, the message is misleading.
@KevinAnderson thanx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.