-1

I had a fellow student ask me this question and I have no idea how to answer it.

The following code works fine.

    int x = 40;
    int y = 35;
    if (x > y)
    {
        int ans = x + y;
    }

However, the code below gives an error saying that the variable declaration isn't allowed where it is. Why isn't it allowed there? NetBeans throws the following exception: Uncompilable source code - Erroneous tree type:

    int x = 40;
    int y = 35;
    if (x > y)
        int ans = x + y;

We are using NetBeans 8.0 Beta if it matters.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user3806867
  • 1
  • 1
  • 3

2 Answers2

1

Not so much a question of working or not working, it's a syntax error. You can't have variable declarations outside of a block.

Why would you even want to do the second pattern? Who is going to use ans?

Thilo
  • 257,207
  • 101
  • 511
  • 656
1

When you scope a variable, it will only be available in that scope.

if (stuff) {
    int i;
    // i available here
}
// i not available here

The first type, the compiler doesn't know if you will use the variable later. it doesn't think there's anything wrong with creating a variable in that block.

In the second type, the compiler knows there is only one statement, because you didn't create a {} block. The variable that you created will definitely not be used, so the compiler is alerting you that you will never be able to use the variable that you defined there.

Strikeskids
  • 3,932
  • 13
  • 27