Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java not have block-scoped variable declarations?

The following method does not work because the inner block declares a variable of the same name as one in the outer block. Apparently variables belong to the method or class in which they are declared, not to the block in which they are declared, so I therefore can't write a short little temporary block for debugging that happens to push a variable in the outer scope off into shadow just for a moment:

void methodName() {
  int i = 7;
  for (int j = 0; j < 10; j++) {
    int i = j * 2;
  }
}

Almost every block-scoped language I've ever used supported this, including trivial little languages that I wrote interpreters and compilers for in school. Perl can do this, as can Scheme, and even C. Even PL/SQL supports this!

What's the rationale for this design decision for Java?

Edit: as somebody pointed out, Java does have block-scoping. What's the name for the concept I'm asking about? I wish I could remember more from those language-design classes. :)

like image 495
skiphoppy Avatar asked Sep 26 '08 18:09

skiphoppy


2 Answers

Well, strictly speaking, Java does have block-scoped variable declarations; so this is an error:

void methodName() {
  for (int j = 0; j < 10; j++) {
    int i = j * 2;
  }
  System.out.println(i); // error
}

Because 'i' doesn't exist outside the for block.

The problem is that Java doesn't allow you to create a variable with the same name of another variable that was declared in an outer block of the same method. As other people have said, supposedly this was done to prevent bugs that are hard to identify.

like image 122
Ricardo Massaro Avatar answered Oct 05 '22 16:10

Ricardo Massaro


I believe the rationale is that most of the time, that isn't intentional, it is a programming or logic flaw.

in an example as trivial as yours, its obvious, but in a large block of code, accidentally redeclaring a variable may not be obvious.

ETA: it might also be related to exception handling in java. i thought part of this question was discussed in a question related to why variables declared in a try section were not available in the catch/finally scopes.

like image 29
John Gardner Avatar answered Oct 05 '22 14:10

John Gardner