2

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

Gray K
  • 67
  • 6
  • 1
    Did you try it? – Juan Mendes Apr 17 '17 at 23:42
  • I did and it worked, but I was not sure is it allowed to do so or not. I also tried to search the web and found nothing about scopes like this. That's why I decided to ask – Gray K Apr 17 '17 at 23:44
  • 1
    [check this](http://stackoverflow.com/questions/241088/what-do-curly-braces-in-java-mean-by-themselves) – José Fonte Apr 17 '17 at 23:45
  • 1
    Possible duplicate of [What is the difference between scope and block?](http://stackoverflow.com/questions/22575444/what-is-the-difference-between-scope-and-block) – Juan Mendes Apr 17 '17 at 23:47

2 Answers2

3

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

Sheinbergon
  • 1,893
  • 1
  • 10
  • 22
2

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
}
Devendra Lattu
  • 2,532
  • 2
  • 15
  • 25