1

Why can not I print the value of j in the last statement although the variable j declared outside the for loop as a local variable?

package practicejava;

public class Query {

    public static void main(String[] args) throws java.io.IOException {
      int j;
      for(int i=1;i<=5;i++) {   
          j=i;
          System.out.println(j);
      } 
      System.out.println("j="+j);
    }
}
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
Tushar Mia
  • 375
  • 2
  • 9
  • Please have a look around and read through the [help center](https://stackoverflow.com/help). In particular [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) Always quote the exact error, rather than just saying you get an error. When someone answers your question as done [here](https://stackoverflow.com/questions/53791297/why-cant-i-write-ch-ch1-instead-of-ch-though-they-have-same-meaning) and [here](https://stackoverflow.com/questions/53793852/in-the-following-code-why-does-the-string-inside-println-method-shows-twice-what) do consider accepting and upvoting it. – Nicholas K Dec 16 '18 at 07:12

1 Answers1

3

The compilation error is

The local variable j may not have been initialized

As the compiler complains, you just need to initialize the variable before using it :

int j = 0;

This will resolve the compilation error.

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
  • but I initialize the variable in the for loop .in the last statement, why dont the initialize value of j in the for loop prints – Tushar Mia Dec 16 '18 at 12:19
  • That's because it is initialized within the `for-loop`'s scope only. Thereby within it's scope there was no issue printing out `j`. – Nicholas K Dec 16 '18 at 12:28
  • that's the ans I was looking for – Tushar Mia Dec 16 '18 at 13:14
  • Thank you! Also, there are other questions that you have asked. Please do consider accepting/upvoting the answers there as well. I have mentioned them as a comment to your question – Nicholas K Dec 16 '18 at 13:30