0

Why we always have to write like

class Main{ 
     public static void main(String[] args){
          bla bla bla...
      }

and why we can't write

class Main{

 public static void main(){
  bla bla bla...
}

just like C and C++.

Jeel Patel
  • 43
  • 6
  • Relevant: https://meta.stackoverflow.com/a/293819/5133585 – Sweeper Aug 16 '21 at 06:08
  • 1
    Does this answer your question? [What is "String args\[\]"? parameter in main method Java](https://stackoverflow.com/questions/890966/what-is-string-args-parameter-in-main-method-java) – Yash Chitroda Aug 16 '21 at 06:09
  • @Yashchitroda I think OP knows what it does, but need clarity on why we need to write main method such a way even if we don't pass command line arguments. – Pradeep Simha Aug 16 '21 at 06:14
  • I know that String[] args is used to provide command line arguments but why is it like that. I mean in C++ we can write string[] if we are going to provide any command line info and if we not then we leave it blank so is there any specific reason why in JAVA it is compulsory to do that ? – Jeel Patel Aug 16 '21 at 06:16
  • @Jeel Patel you may consider this : https://www.javatpoint.com/java-main-method – Yash Chitroda Aug 16 '21 at 06:17
  • check this https://stackoverflow.com/questions/31130229/why-does-java-specifications-want-the-main-method-of-a-program-to-be-void-only#31469676 –  Aug 16 '21 at 06:20
  • Because some other Java projects do want to provide the command line arguments. A generic platform like Java is a consensus between various needs and may include features one or another project does not require. If your specific program does not need java.util.zip.Adler32, does not mean it is a useless class that should not be included. – Audrius Meškauskas Aug 16 '21 at 07:18
  • Because That's The Way They Designed It. – user207421 Aug 16 '21 at 08:17

1 Answers1

2

It's the Java specification for main method.

The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String.

Ref: 12.1.4. Invoke Test.main

seenukarthi
  • 8,241
  • 10
  • 47
  • 68