DEV Community

Deepikandas
Deepikandas

Posted on • Edited on

#24 known is a drop! main method in JAVA

It's the entry point for your application and will subsequently invoke all the other methods required by your program.

Modifiers in main method:
The modifiers public and static can be written in either order (public static or static public)
public → JVM must access it from outside the class.
If you make it non-public, JVM cannot access it, and you’ll get an error.
static → JVM can call it without creating an object of the class.
Return type of main()
main method signature is void
It does not return anything to the JVM directly.
That’s why the return type is void.

Returning a value to the OS
When you call:
System.exit(0);

String args[]

  • The main method accepts a single argument: an array of elements of type String.

  • Each string in the array is called a command-line argument.

  • These are used to give input during run time.

  • Actually not during run time, before the program runs itself ,we give input.

All syntax are correct:

  • public static void main(String... args)
  • public static void main(String[] value)
  • static public void main(String[] args)

In cmd prompt:
We have to give values to command line arguments at the time of run.
eg: java filename input1 input2

🟩input1 is stored in args[0],
input2 is stored in args[1].

🟩all inputs are taken in the form of Strings.

To parse the string values:
🟩 if we want to perform any arithmetic operations,
we have to parse the value using Integer.parseInt(String args[0])
i.e., converting String to primitive int type

🟩 Same for other float values, boolean. We have to parse using corresponding Wrapper class parse method.

*In Eclipse * Right click->Run configurations->select Arguments tab-> enter values separated by space.(not commas in between)

*How Scanner class differs from command line arguements? * If we use Scanner class, we can inform the user to enter values as inputs are fed during run time
but using command line args, we cannot prompt.

Can main be overloaded?
✅ Yes. You can define multiple main methods with different parameters in the same class.
JVM behavior:
The JVM only automatically calls public static void main(String[] args) as the program entry point.
Overloaded main methods are not called automatically; they must be called explicitly from the standard main or elsewhere.

public static void main(String[] args) { }      // standard entry
public static void main(int number) { }         // overloaded
public static void main(String message) { }     // overloaded
public static void main(int a, int b) { }       // overloaded
Enter fullscreen mode Exit fullscreen mode

main Can Be in Multiple Classes:

Each class can have its own main method.
You can choose which class to run from the command line.

Top comments (0)