0

if we declare a variable before a for loop and we are declaring same name variable in for loop statement. we are getting error in java. why as both have different scope. why compiler is unable to recognize it.

public class Main {

    public static void main(String[] args) {
        int [] arr = {0,1,2,3,4,5,6,7,8,9};
        int j = 0;
        int i = 0;  // first declaration
        for(int i = arr.length-1,j = 0; (arr.length)/2<=i; i-- ) { // second declaration
           int temp = arr[i];
           arr[i] = arr[j];
           arr[j] = temp;
           j++;
        }
        for(int i = 0 ; i< arr.length;i++) {
            System.out.println(arr[i]);
        }
        System.out.println(j);
    }
}
AP11
  • 617
  • 4
  • 11
  • 1
    You need to use `i = arr.length-1` (without the `int`) in the loop if you want to declare the variable before the loop but want to set the initial value at the start of the loop. You can't declare the same variable twice. – Nexevis Oct 14 '21 at 13:43
  • 4
    because variable names need to be unique per scope. In every scope there can only be one variable named `i` because your compiler needs to be able to know what you are trying to reference when you write `i` – OH GOD SPIDERS Oct 14 '21 at 13:44
  • "we are getting error. why?" - Why shouldn't you? This _is_ an error, you're basically declaring 2 different things with the same name in the same scope (at least they share the scope of the loop) - any access to those would only lead to confusion, i.e. which `i` is meant? There's also no way to tell the compiler "no, I mean the other one" like with fields and local variables where `i` would mean the local variable and `this.i` would mean the field (or `TheClass.i` would be used for static variables). – Thomas Oct 14 '21 at 13:45
  • 2
    Does this answer your question? [question about variable scope and shadowing in java](https://stackoverflow.com/questions/4623334/question-about-variable-scope-and-shadowing-in-java) – Quazan Oct 14 '21 at 13:54
  • @OHGODSPIDERS that is not the real reason, as some other languages allow this kind of shadowing. There is no *inherent* problem, it's a choice the language designers made to ban this shadowing. – harold Oct 14 '21 at 13:54
  • answer is not cleared if compiler is doing so... if we declare that variable only in for loop statement then scope of that variable have to be in whole method. why it is only to that particular block – vishal joshi Oct 14 '21 at 14:12

0 Answers0