-2

I'm trying to compile my java code, but it's not compiled. I'm commanding javac File.java

File.class class file is not created yet, but my program is working perfectly. What kind of problem is thik

  • Is it possible to add the source of File.java? And also how you are trying to run it? – Jay Dec 27 '20 at 22:56
  • javac File.java then enter, I know that javac will compile my File.java to Fila.class but without class file my program is run, any class file is not created yet :( – MD Mahbub SK Dec 27 '20 at 23:02
  • but there are no answer that I'm finding right now. – MD Mahbub SK Dec 27 '20 at 23:13
  • 1
    @MDMahbubSK *"I know that javac will compile my File.java to Fila.class"* Not always, see answer below. --- *"but without class file my program is run"* `javac` will never run the program, only compile it. In Java 11 or later, you can use `java File.java` (`java`, not `javac`) to compile and run the program in one operation, which will not create a `.class` file on the file system. – Andreas Dec 27 '20 at 23:50

1 Answers1

1

TL;DR It is most likely that the File.java file contains a non-public top-level class of a different name, so the compiler created a .class file with the actual name of the class. Rename the class or the source file, so the names match.


More than 99.999% of the time, javac File.java will create a File.class file if compilation completes without error, but that is not always the case.

A .java file can contain many classes, and each class is compiled to a .class file named after the class. E.g.

File.java

class A { // top-level class
    class B { // nested class
    }
    void x() {
        class C { // local class
        }
        new Object() { // anonymous class
        };
    }
}
class D { // top-level class
}

This will create the following files:

A.class
A$B.class
A$1C.class
A$1.class
D.class

As you can see, no File.class was created.

When compiling from the file system, which is pretty much always the case, the following rules are applied by the compiler:

  • There can be at most 1 top-level class that is public.
  • If the .java file contains a public top-level class, the .java file must be named the same as that public class.

General recommendations:

  • Have only one top-level class in a .java file.
  • Even if the top-level class is not public, name the file after the class.

The two recommendations help ensure that both the compiler and us mere humans can find the source file containing a class.

Andreas
  • 154,647
  • 11
  • 152
  • 247