Reputation: 25
Why can't i
be initialized before declaring it in code 1 but it can be in code 2 :
class Code1 {
void methodOfCode1() {
// System.out.println(i); can't use a local field before it is defined
// i = 10; can't initialize a local field before it is defined
int i;
}
}
class Code2{
static
{
i = 10; //A field can be initialized before it is defined.
}
static int i;
}
Upvotes: 2
Views: 99
Reputation: 4207
In Java, a variable's type must be declared before it can be used.
For example:
System.out.println(i); // for this statement i is unknown/undefined...
i = 10; // same for above...
EDITED :
First inside class Code1
,
you haven't declare variable before use it, which is against of Java Standard API so obviously compiler will complain.
while into class Code2
case,
you have declare 'static' both instance
as well as block
.
so it does not required any instance to load it. (review static concept in depth will let you to the correct direction)
Upvotes: 0
Reputation: 7928
Java is strongly-typed, you can't use something that you don't know what it is. For instance, a method is different if it receives a String
or if it receives an int
, so the compiler must be able to know which is the proper method to be invoked
For instance, this is valid:
public void dealWithIt(int val){
val++
System.out.println(val);
}
public void dealWithIt(String val){
System.out.println(val);
}
The compiler can't assign a value to a variable before know what type of variable it is.
Upvotes: 0
Reputation: 184
Because compiler must know where this variable is stored and how many bytes it have to use. If I tell computer var=97 before initializing, it cannot know where this "var" variable is stored. Also if "var" is char , computer needs one byte to store in RAM. However it also can be an integer which is 4 bytes(depends on different systems). Therefore, there would be an ambiguous situation for the system.Compiler does not allow that , reasonably.
Upvotes: 0
Reputation: 3711
The answer is order of execution.
Code executes sequentially, you must define what something is before you use it. Therefore in a method you must declare a variable before you use it.
In Java the compiler initializes your class
in multiple passes. It first runs through and declares all of the static members, then it sets the default values for all static members. This all happens before any methods (static or not) are executed.
Upvotes: 3
Reputation: 49
During initialise a variable, some amount of memory is allocated based on datatype.
Unless you allocate memory, you can't initialize value.
Upvotes: 0
Reputation: 8303
It's the scope of the variable & the lack of type prior to its use: you have yet to define i
. You must define a variable before it can be used:
int i = 0;
System.out.println(i); // works
System.out.println(j); // will not work
byte j;
Here's the Java Language Specification giving you the detail.
Upvotes: 0