title: Java compilation of a .java file without a public class
body: <p>Okay, so a java source file <em>must</em> have at least one public class and the file should be called "class-name.java". Fair enough.</p>
  
  <p>Hence, if I have a class, then the following would compile:</p>
  
  <pre><code>public class HelloWorld {
      public static void main(String[] args) {
          System.out.println("Hello World!"); // Display the string.
      }
  }
  </code></pre>
  
  <p>But what bugs me is that if I remove the 'public' access modifier from the above code, the code still compiles. I just don't get it. Removing it, the code looks like:</p>
  
  <pre><code>class HelloWorld {
      public static void main(String[] args) {
          System.out.println("Hello World!"); // Display the string.
      }
  }
  </code></pre>
  
  <p>In the above code, since I removed the <code>public</code> access modifier, my class has <code>default</code> or <code>package</code> access, i.e. it can't be accessed from the outside world, only from within the package. </p>
  
  <p>So my question is, how does the above code compile ? The file <code>HelloWorld.java</code> in this case does not have a <code>public</code> HelloWorld class (only a package-private HelloWorld.class) and thus to my understanding should not compile.</p>