0
In basic hello world program, I replaced void with int and added return 0 at end of main function. I am getting as "no output"
I am experimenting on java (I am a newbie to java) from the knowledge I have on C. https://code.sololearn.com/cK7jjK5gkHHS/?ref=app
7 Réponses
+ 1
if you run this together :)
class MyClass {
public static int main(String[] args) {
System.out.println("Hello World");
return 1;
}
}
class Program {
public static void main(String[] args) {
System.out.println( MyClass.main(args) );
}
}
+ 2
JaguR as Martin mentioned, your main method signature MUST match exactly the same
public static void main(String[] args)
No exceptions, no variations. Main method cannot return anything, because there is no caller to return to.
When we want to close the program with a specific status code, by terminating the JVM, we normally write
System.exit(1);
+ 1
Tibor Santa oh that's all I wanted to know. Thank you. You saved me from unnecessary efforts.
+ 1
Martin Taylor ok, got it.Thank you.
0
Martin Taylor Thank you for your detailed explanation.
Actually I swapped public and static 1st and the code compiled perfectly. So left it that way. Now my doubt is can't I replace void with main and add return 0 at the end of main function in order that the code compiles as earlier in Java? (I experimented this in C and it worked fine.)
0
zemiak Thanks for correcting my program and providing the right one I am actually looking for.
But, why do I need to add the rest of the part beginning from "class program ...."? Could you please explain meaning of each line and why you added add it?
0
public static void main(String[] args) {
is really required, here is right main() in class Program and Program.Main() calls your MyClass.main() as ordinary method
look at this funny article
https://www.geeksforgeeks.org/valid-variants-main-java/