title: Initialisation of a variable inside a loop
body: <pre><code>class Spaces {
  public static void main(String args[])
  throws java.io.IOException{
  
      char ch;
      int space = 0;
  
      do {
  
          ch = (char) System.in.read();
          if (ch == ' ') space++;
  
      } while (ch != '.'); //Stop if fullstop is provided
  
  System.out.println("No. of spaces: " + space);
  }
  </code></pre>
  
  <p>The following code above is completely correct and is doing exactly what it is intended to do.(To read characters until fullstop is pressed, then tell the user how many spaces have been entered). Although if I initialise the variable outside the do-while loop like in the following code:</p>
  
  <pre><code>class Spaces {
  public static void main(String args[])
  throws java.io.IOException{
  
      char ch = (char) System.in.read();
      int space = 0;
  
      do {
  
          if (ch == ' ') space++;
  
      } while (ch != '.'); //Stop if fullstop is provided
  
  System.out.println("No. of spaces: " + space);
  }
  </code></pre>
  
  <p>The program is refusing to stop. When I enter the full stop, the program is not stopping. I do know that declaring a variable inside the loop would mean that it is unavailable elsewhere outside that loop. But variable declared outside the loop (like in second set of code) should work in the loop and elsewhere. So I am not getting why the second set of code is not valid (the program runs, there is no compiling error, but when full stop is entered it keeps going).</p>
  
  <p>I also understand this is a very basic question compared to the ones that get asked here. But I honestly couldn't find an answer. Thank you in advance.</p>