Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I was under the impression that the main method had to have the form "public static void main (String[] args){}", that you couldn't pass int[] arguments.

However, in windows commandline, when running the following .class file, it accepted both int and string as arguments.

For example, using this command will give the output "stringers": "java IntArgsTest stringers"

My question is, why? Why would this code accept a string as an argument without an error?

Here is my code.

public class IntArgsTest 
{
    public static void main (int[] args)
    {

        IntArgsTest iat = new IntArgsTest(args);

    }

    public IntArgsTest(int[] n){ System.out.println(n[0]);};

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
479 views
Welcome To Ask or Share your Answers For Others

1 Answer

Everything passed into main method, the one used by the JVM to start a program, is a String, everything. It may look like the int 1, but it's really the String "1", and that's a big difference.

Now with your code, what happens if you try to run it? Sure it will compile just fine since it is valid Java, but your main method signature doesn't match the one required by the JVM as the starting point of a program.

For your code to run, you'd need to add a valid main method like,

public class IntArgsTest {
   public static void main(int[] args) {

      IntArgsTest iat = new IntArgsTest(args);

   }

   public IntArgsTest(int[] n) {
      System.out.println(n[0]);
   };

   public static void main(String[] args) {
      int[] intArgs = new int[args.length];

      for (int i : intArgs) {
         try {
            intArgs[i] = Integer.parseInt(args[i]);
         } catch (NumberFormatException e) {
            System.err.println("Failed trying to parse a non-numeric argument, " + args[i]);
         }
      }
      main(intArgs);
   }
}

And then pass some numbers in when the program is called.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...