Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does overloading the main method give a syntax error?

import java.util.*;
public class Overload {
    public static void main(String...args) {
        System.out.println("in main 1");
    }
    public static void main(String args[]) {
        System.out.println("in main 2");
    }
}

I was checking if both the main methods have standard signature which one will get executed but when I compile it, it shows error. why is it so?

like image 634
Pranav Tyagi Avatar asked Sep 13 '26 07:09

Pranav Tyagi


2 Answers

Varargs are basically compiled into single array. Hence, you have 2 methods which are the same

Your code (changed one of the main, it's now a valid code):

import java.io.PrintStream;

public class Overload {
  public static void main2(String... paramVarArgs) {
    System.out.println("in main 1");
  }

  public static void main(String[] paramArrayOfString) {
    System.out.println("in main 2");
  }
}

This code compiled, and decompiled with a bytcode viewer:

public class Overload {

     public Overload() { // <init> //()V
         L1 {
             aload0 // reference to self
             invokespecial java/lang/Object <init>(()V);
             return
         }
     }

     public static varargs main2(java.lang.String[] arg0) { //([Ljava/lang/String;)V
         L1 {
             getstatic java/lang/System.out:java.io.PrintStream
             ldc "in main 1" (java.lang.String)
             invokevirtual java/io/PrintStream println((Ljava/lang/String;)V);
         }
         L2 {
             return
         }
     }

     public static main(java.lang.String[] arg0) { //([Ljava/lang/String;)V
         L1 {
             getstatic java/lang/System.out:java.io.PrintStream
             ldc "in main 2" (java.lang.String)
             invokevirtual java/io/PrintStream println((Ljava/lang/String;)V);
         }
         L2 {
             return
         }
     }
}
like image 189
Janekx Avatar answered Sep 15 '26 21:09

Janekx


Using an ellipsis (...) is just syntactic sugaring that allows you to pass several comma-delimited arguments instead of explicitly declaring an array. From within the method, for all intents and purposes that argument is an array. So, you're essentially defining two methods with the same signature (public static void main(String[])), which is not allowed, regardless of the fact that it's the special main method.

like image 29
Mureinik Avatar answered Sep 15 '26 21:09

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!