1

I want to know about that error "variable Y not initialized in the default constructor" what happens internally...

static final int y;
public static void main(String[] as){
System.out.println(y);
}
  1. I've used static variable not instance but sill i got.
  2. Why it is only initilzed in sameline or static block .
  3. What is the roll of default constructor.

3 Answers3

0
  1. I've used static variable, not instance, but still I got variable Y not initialized in the default constructor.

The error is misleading. The default constructor part should be ignored. The rest of the error is correct.

  1. Why it is only initialized in same line or static block.

It must be initialized before the class is put into service. Those are the only two places where you can do that, so it must be initialized in exactly one of them.

  1. What is the role of default constructor.

As mentioned for #1, it has no role here.

Andreas
  • 154,647
  • 11
  • 152
  • 247
0

1. If you try to use variables before they have a value, you will usually get a NullPointerException telling you that this variable has no value except null.

2. You have "created" a constant which must be assigned before creating the object. That can be done in the static-block

static {
   //assignment - no logic here!
}

or directly at "create".

3. The standard constructor is only for creating objects, because there is no room for assignments or logic (never logic in the constructor). Unless you change it.

Jerome Wolff
  • 356
  • 3
  • 19
0

I'hve used static variable not instance but sill i got

It's not because of static keyword; it's because of final keyword which requires y to be initialized. If you remove the keyword, final from the declaration, it will compile without any problem.

Why it is only initilzed in sameline or static block .

Again, if it has been declared as final, it has to be initialized with the declaration. Initializing it in a static block won't work.

What is the roll of default constructor.

Check Java default constructor

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110