2
public class TestVariableDeclaration{
    int j;  // ERROR
    j=45;   // ERROR

    static{
        int k;
        k=24;

    }

    {

        int l;
        l=25;
    }

    void local(){
        int loc;
        loc=55;
    }

}
  1. In the above why can't I declare a variable "j" and then initialize directly under a class
  2. I can declare and then initialize in the same manner under a Method,Static/Instance initialization block?
  3. What makes the difference, I am aware about the fact that Java does not support Declaring and then initializing a instance variable. What's the reason behind that??
4
  • 1
    The compiler isn't smart enough Commented Oct 8, 2013 at 7:04
  • int j=45; you can initialize while declaring Commented Oct 8, 2013 at 7:05
  • May i know the reason why declaration and then initialization of the variable is not possible?? Commented Oct 8, 2013 at 7:08
  • 1
    because at the possion where you wrote j=45; only declarations are allowed but not statements. Commented Oct 8, 2013 at 7:10

3 Answers 3

2
  1. you can declare on class level with int j = 45; as mentioned by Subhrajyoti Majumder
  2. k is in a special function/method, call it the static initializer. it is executed when class is loaded. k is only known inside this method
  3. l is in a special method which is executed on class instantiation. l is only known in this method.

This is very basic java stuff.

(edit:typos)

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

Comments

0

You cannot use a variable before declaring it under normal circumstances. So

j=45; 

at the top will fail since j hasn't been declared yet.

Unless I am not getting your question, this is very much possible with:

class SomeClass {
    int j; // declare it
    {
        j=45; // initialize it
    }
}

OR even more concise:

class SomeClass {
    int j = 45; // declare and initialize
}

Comments

0

Why dont you simply initialize and declare it together like this -> int j=45;? It works that way for me..

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.