Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

main method as final in java

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?

like image 741
Gpar Avatar asked Nov 03 '14 09:11

Gpar


3 Answers

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.

like image 179
Eran Avatar answered Nov 09 '22 03:11

Eran


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.

like image 34
hchawla Avatar answered Nov 09 '22 04:11

hchawla


The main method has to be accessible from the outside. Hence, in your case the application will compile but throw an execution at runtime.

like image 39
Stefan Freitag Avatar answered Nov 09 '22 04:11

Stefan Freitag