Jp Reddy
Jp Reddy

Reputation: 131

Java Declare a variable and then initialize it.?

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??

Upvotes: 2

Views: 348

Answers (3)

Hajo Thelen
Hajo Thelen

Reputation: 1135

  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)

Upvotes: 2

Sid
Sid

Reputation: 371

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

Upvotes: 0

anubhava
anubhava

Reputation: 784908

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
}

Upvotes: 0

Related Questions