❔Interview Questions
Why is the main() method static in Java?
Because the main() method needs to be called without creating an object of the class. Being static allows it to be directly invoked via the class name.
Can the main() method be overloaded in Java?
No, the main() method cannot be overloaded as Java runtime only calls the main() method that has the exact signature of:
public static void main(String[] args)
Can the main() method be declared final in Java?
Yes, declaring the main() method as final prevents it from being overridden in subclasses. This can be done to prevent tampering with the main method's logic.
What is the significance of the String array parameter passed to the main() method?
The String array (String[] args) contains any command line arguments passed while invoking the class. We can access and use these arguments in the main() method.
Can the main() method call itself recursively in Java?
Yes, the main() method can call itself recursively similar to any other Java method. However, extreme care must be taken to ensure termination conditions are met to prevent infinite recursion.
What if we declare the main() method as private in Java?
Compilation error. The program will not compile if main() is declared private since it needs to be visible for the runtime to invoke it.
Is it mandatory to have a main() method in a class for it to run in Java?
No, if no main() method is present, the class can still be used by calling methods on an instance of that class from another class having main().
What arguments get passed to the main() method in Java by default?
By default, the main() method is called with no arguments. We have to explicitly pass command line arguments at runtime for them to be received in the main() method.
Last updated