Java Interview Question and Answer Why main method in java public static void

preview_player
Показать описание

Why main method in Java is "public static void" ? Java Interview Question and Answers ?

Main method in Java is entry point for any core Java program. In core Java program, execution starts from main method when you type java main-class-name, JVM search for public static void main(String args[]) method in that class and if it doesn't find that method it throws error NoSuchMethodError:main and terminates.

Main method has to strictly follow its syntax; other wise JVM will not be able to locate it and your program will not run.

Why main method is public in Java ?
Java specifies several access modifiers e.g. private, protected and public. Any method or variable which is declared public in Java can be accessible from outside of that class. Since main method is public in Java, JVM can easily access and execute it.

Why main method is void in Java ?
Since main method in Java is not supposed to return any value, its made void which simply means main is not returning anything.

Why main method in Java is "public static void" ? Java Interview Question and Answers ?

Why main method is static in Java ?

Since main method is static Java virtual Machine can call it without creating any instance of class which contains main method.

If main method were not declared static than JVM has to create instance of main Class and since constructor can be overloaded and can have arguments there would not be any certain and consistent way for JVM to find main method in Java.

Anything which is declared in class in Java comes under reference type and requires object to be created before using them but static method and static data are loaded into separate memory inside JVM called context which is created when a class is loaded. If main method is static than it will be loaded in JVM context and are available to execution.

A Job Portal

Other Top Job Portals

Are you looking for a new Job ?
Рекомендации по теме