-4

I am trying to visualize the scope of the variables in a given Java program. How can I name each scope between "{" "}"? i.e. i wanted to display the variables or objects in a tree structure by seeing which a programmer will know the scope of variable or object easily. I have written a program to calculate the "{" "}" and whether a conditional statement or looping statement occurs on a single line, without any "{" "}". My question is! is there already any other tool or concept to do the same or we have write on our own. I am sorry i dont know how to put it more clear.

1
  • Not sure what your question is. Why does a scope need a name?
    – DNA
    Feb 23, 2012 at 9:15

2 Answers 2

2

how can i name the each scope between "{" "}"

It is not clear why you need to name the block. Most IDEs don't do this: they may instead use highlighting to show which opening and closing braces match. I think you mean that you wish to identify each matching pair of braces, but you don't actually need to name them.

Either way, you will have to parse the source code to correctly match the braces. Note that it is not sufficient to just count the braces without parsing the code because braces inside for example comments and strings do not start or end scopes.

what if a conditional statement or looping statement occurs with single line and have no "{" "}".

It's not legal to create variables in the body of a conditional statement (or in the body of a loop statement) unless that body is a block (i.e. surrounded by braces). This is because the definition of Block is:

BlockStatement:
    LocalVariableDeclarationStatement
    ClassDeclaration
    Statement

And IfThenStatement is defined as folows:

IfThenStatement:
    if ( Expression ) Statement

The definition of Statement does not include LocalVariableDeclarationStatement (except inside a block).

1
  • Except in a loop declaration, e.g. for(int i = 0, i < 9; i++) System.out.println(i);
    – DNA
    Feb 23, 2012 at 9:19
1

You can name the scopes whatever you want. If you want to do this in code you can add labels to them.

OUTER: {
    // code
    INNER: {
        if(flag)
           break OUTER;
    }
    // code
}

You can't declare variables in a stand alone statement (without a { }) The only exception if for/for-each loops which declare variables.

Not the answer you're looking for? Browse other questions tagged or ask your own question.