why we have to declare the main function inside the class and we have to save the file name ( .java) as the class (which contains the main function) name why............what's the reason ?

Can we use another name for the saving the .java file ...........

Dani AI

Generated

To answer : Java is a class-based language, so the program entry point (the main method) lives inside a class. The JVM starts by loading a class you name on the command line and invoking its main method — so the method can be in any class, but it must match the exact signature the launcher expects: public static void main(String[] args) (a varargs form String... is also accepted).

The file-name rule you noticed comes from the compiler, not the JVM. If a top-level class or interface in a source file is declared public, the source file must be named exactly after that public type (including case) with a .java extension. If there is no public top-level type, the source file name can be different from the classes it contains. Example:

/* File: Runner.java */
public class Runner {
    public static void main(String[] args) {
        System.out.println("Runs from Runner");
    }
}
/* File: AnyName.java */
class Helper {
    public static void main(String[] args) {
        System.out.println("This also runs even though file is AnyName.java");
    }
}

Compile and run with:

javac Runner.java
java Runner

Troubleshooting tips: if you see "class X is public, should be declared in a file named X.java", rename the file or remove public. If the JVM complains "Main method not found" check that the signature is exact (public static void main(String[]) or varargs), that the method is public and static, and that you run the class by its full name (including package). Also watch case sensitivity and package/directory layout. Contrary to ’s brief reply, you can save a source file under a different name provided you don’t violate the public type rule; was right that the language spec defines these rules.

Recommended Answers

All 2 Replies

Can we use another name for the saving the .java file ...........

off course you can, you just won't be able to compile the file any more, that's all.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.