I have a java file containing more than one class, out of which one is public. If main method is inside a non-public class. I can't run that java file. Why is that? and there is no compilation error as well. If so, how can I use that main method?
Yes, we can declare the main method as private in Java. It compiles successfully without any errors but at the runtime, it says that the main method is not public.
Declaring the main method private or, protected But, at the time of execution JVM does not consider this as the entry point of the program. It searches for the main method which is public, static, with return type void, and a String array as an argument. If such a method is not found, a run time error is generated.
Yes. Things like libraries don't have a main method. The main method is the entry point for the program, so you'll have to have a main method somewhere or the code won't execute, but not necessarily in any given Java file.
Though Java doesn't prefer main() method called from somewhere else in the program, it does not prohibit one from doing it as well. So, in fact, we can call the main() method whenever and wherever we need to.
there is something i would like to add although everybody here believes that a public is necessary for the main in a class and that it won't work without main
you can have as many mains in a class as you desire, and you can have them without a public access modifier. but be careful, only that class which is named after the file can be public what i mean is if you name your file a.java , then only the class with name a can be public, none other can have this facility
here is a code to show this : as you can see the name of the file is helping.java
//:initialization/helping.java
class b{
public static void main(){
System.out.println("hello its b");
}
}
class helping {
static void f(float i, Character... c) {
System.out.println("first");
}
static void f(char a, Character... args) {
System.out.println("second");
}
public static void main(String[] args) {
f(1,'a');
f('a','b');
c.main();
}
}
class c{
public static void main(){
System.out.println("hello its b");
}
}
//:~
/*
* output:
* first
* second
* hello its b
* */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With