Gray K
Gray K

Reputation: 67

Custom variable scope

Is it allowed to just place some curly braces without any if/for/etc statements to limit the variable scope?

An example:

public void myMethod()
{
    ...
    {
        int x;
        x = 5;
    }
    ...
}

I may want to do this, so I know for sure I won't access/change the variable outside the scope and that it will be destroyed beforehand

Upvotes: 2

Views: 54

Answers (2)

Devendra Lattu
Devendra Lattu

Reputation: 2802

The curly braces { .. } limit the scope of variables to the block.
However, changes can be made to global variables falling into the scope of { .. } block.

int x = -1;
double y = 5;
{
    x = 10;
    y = 100;
    char c = 'A';
}
System.out.println(x + " " + y); // 10 100.0
System.out.println(c); // Compile time error and out of scope

{
    c = 'B';  // Compile time error and out of scope
}

Upvotes: 2

Sheinbergon
Sheinbergon

Reputation: 3063

Yes, it's allowed. Just try and see for youtself

Upvotes: 3

Related Questions