Reputation: 39
the following code gives an error, because the variable m was defined twice.
class one {
public static void main(String args[]) {
int m=10;
int m=10;
}
}
but when the declaration is done inside a loop, it is OK, even though m
is still being defined twice.
class one {
public static void main(String args[]) {
for(int i=1;i<=2;i++) {
int m=10;
}
}
}
and the compiler does not give back an error message.
can you explain the differences between the two, and how come sometimes i can declare the same variable twice inside the same method, and sometimes not?
Upvotes: 2
Views: 3982
Reputation: 4559
In simple words, you are not declaring this variable twice in second example. As variable lifespan ends on the closing }
of the block in which it was declared, by the time you declare m
in second iteration, first one is "dead". This is why you can do it in a loop.
In first example you declare two variables with the same name in the same code block, which are supposed to "live" simultaneously. This is forbidden as you can't tell which variable you refer too by writing m
.
Upvotes: 0
Reputation: 33534
- In the First code you have declared m twice in the same scope, and it continues till the main() method ends.
- Where as within the loop
everytime a primitive int variable m
is created with a value, so its obviously not a problem.
Upvotes: 0
Reputation: 2866
you get the error is because you defined the same variable twice in the same block (scope). when you run inside a loop, you "open" a new scope for every iteration of the loop, so you can define a variable that is visible only within this scope (won't be accible outside the loop though). for instance, if you had written something like that:
class one {
public static void main(String args[]) {
{
int m=10;
}
{
int m=10;
}
}
}
it would have been compiled just fine, because the variables of the same name, does not share the same scope.
Upvotes: 0
Reputation: 73
It's creating an error in the first one because you are declaring the varible twice.
Upvotes: 0
Reputation: 21320
You cannot declare a variable with the same name more than once in a block of code.
In first case, you are declaring the same variable in a block of code i.e. main.
In second case, after the first iteration of for loop, variable m
is destroyed and recreated over the second iteration
Upvotes: 0
Reputation: 15664
For the first case m is referenced till the end of the main method so you can't have two variable of the same name in the same scope.
Whereas in the second case, for every time the loop executes, m for the last iteration is no longer referenced and hence you are able to redeclare and reinitialize it.
Upvotes: 2