Why is it that curly braces do not define a separate local scope in Java? I was expecting this to be a feature common to the main curly brace languages (C, C++, Java, C#).
class LocalScopeTester
{
public static void main(String... args)
{
Dog mine = new Dog("fido");
if (mine.getName().equals("ace"))
{
Dog mine = new Dog("spot"); // error: duplicate local
}
else
{
Dog mine = new Dog("barkley"); // error: duplicate local
{
Dog mine = new Dog("boy"); // error: duplicate local
}
}
}
}
Local scope is a characteristic of variables that makes them local (i.e., the variable name is only bound to its value within a scope which is not the global scope).
Global variables are declared outside all the function blocks. Local Variables are declared within a function block. The scope remains throughout the program. The scope is limited and remains within the function only in which they are declared.
There are three types of variables in java, depending on their scope: local variables. instance variables. class variables (static variables).
They do define a separate local scope, but you still cannot mask local variables from a parent scope (but you can of course mask instance variables).
But you can define new variables (with different names) and their scope will be limited to within the braces.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With