-4
import java.io.*;
class a{}
class b{
    public static void main (String[] args) {
        System.out.println("Geeks..");
    }
}

If in above snippet,

  1. I make class b as public, it gives compiler error:

    class b is public, should be declared in a file named b.java

    Why it then doesn't expect main in class a after making b as public?

  2. I make class a as public,it again gives : main not found in class A.

  3. If I make both classes public, it gives: class b is public, should be declared in a file named b.java

  4. If I change it to below:

    public class b{
        public static void main (String[] args) {
            System.out.println("Geeks..");
        }
    }
    class a{}
    

It gives proper output: Geeks..

Please clarify the relation between order of classes, public and non public class, main method and file name.

Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175
Aditii
  • 5
  • 3
  • What is the name of this source file? You may have **only** one public class in your source file, and if you have a public class, that class **must** be named to match the file name, and the `main` method **must** be in that class and not a different one. – Karl Knechtel May 30 '22 at 09:18
  • from the title "*main method not found in class a*" -> should be obvious - `main` is declared only in class `b`! For posted code, you have to use `java b` to execute that main method, since the method is in class `b` (not `a`). – user16320675 May 30 '22 at 09:31
  • Usually, in Java you have only one public class per file. And this file should be named like the class. – Valerij Dobler May 30 '22 at 09:52
  • That doesnt explains why the output of my code snippet is like that, please read the question entirely with all 4 points – Aditii May 31 '22 at 16:11
  • 1
    maybe you should have selected a better title... and add how you are executing that file, is it `java filename.java` (without compiling) ? That is called Source-File mode, which executes a source file without need to explicitly compile - it will compile and start first class' main method. See [doc](https://docs.oracle.com/en/java/javase/18/docs/specs/man/java.html#using-source-file-mode-to-launch-single-file-source-code-programs): "*... In source-file mode, the effect is as though the source file is compiled into memory, and the first class found in the source file is executed. ...*" – user16320675 Jun 01 '22 at 12:46

0 Answers0