简体   繁体   中英

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?

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.

You have the main method but since the modifier is final JVM wont be able to run the main method of the program.You wont see any compilation error.

You can run the program in eclipse when you make the modifier change of final to public

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM