Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

local scope in Java

Tags:

java

scope

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
            }
        }
    }
}
like image 575
H2ONaCl Avatar asked Aug 31 '11 11:08

H2ONaCl


People also ask

What are local scopes?

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).

What is local scope and global scope in Java?

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.

What are the 3 different scopes of variables in Java?

There are three types of variables in java, depending on their scope: local variables. instance variables. class variables (static variables).


1 Answers

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.

like image 76
Thilo Avatar answered Sep 28 '22 07:09

Thilo