Archive for July 27th, 2010

More fun with Java (scope and duplicates)

July 27th, 2010 | Category: C++, Java, Programming

I thought this was interesting… In Java, a block scoped variable may conflict with a local variable declared later in method scope, but not previously (as shown below):

class A{
  public static void main(String args[]){
    {int k = 5;}
    int k = 12; //this is OK
    {int k = 22;}//this is not....

This is not the same as C++ where this compiles happily:

int main(){
  {int i;}
  int i;
  {int i;}
  return 0;

Usually C++ has the more obscure behavior….

Comments are off for this post