I saw this code in one of the certification exams:
public class SimpleClass
{
int num;
final static void main(final String args[])
{
String s1="new";
String s2="String";
String s3="Creation";
System.out.println(s1+s2+s3);
}
}
I know that final methods are ones which are not possible to override. I also know that if the usual signature of the main
method is altered, it will be treated as any other ordinary method by the JVM, and not as main()
.
However, the options given to me were:
1> Code won't compile
2> Code will throw an exception
3> will print newStringCreation.
It's not possible to run this program on eclipse IDE. Can anyone explain what should be the answer and why?
Ok let me put my question like this - When I execute my program, what will happen? Which of the 3 options above should I choose?
final static void main
won't run, since main is not public.
public final static void main
will work.
At least that's the behavior on my Eclipse IDE.
The Code will compile without any problems but it will throw a run-time exception saying "main method not public". The main method has to be public because it has to be called by JVM which is outside the scope of the package and hence would need the access specifier-public. If you are unable to run it in eclipse, try the archaic method of saving the file in a notepad with filename.java. Go to cmd and reach the file location..If on desktop, use cd desktop! Use the following commands to run the file-
javac filename.java
java filename
You will see the required run-time exception that I mentioned above.
The main
method has to be accessible from the outside. Hence, in your case the application will compile but throw an execution at runtime.
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