Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › How Java Runs — JDK, JRE, JVM & Your First Program

Why must a public class's file name match the class name?

Level I · BeginnerHow Java Runs — JDK, JRE, JVM & Your First Program
Short answer

The Java compiler requires that a public top-level class live in a file of the same name (Order in Order.java), so tools and the class loader can locate a class predictably from its name.

Explanation

If they do not match, javac reports an error. Non-public top-level classes do not have this restriction, which is why small demo files sometimes use a package-private class to avoid the filename constraint.

Common mistakes
  • Thinking every class must match its file name — only the public top-level class must.
  • Putting two public top-level classes in one file.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for How Java Runs — JDK, JRE, JVM & Your First Program.

Practise free

More on How Java Runs — JDK, JRE, JVM & Your First Program