What does “String[] args” contain in java?

后端 未结 8 1863
终归单人心
终归单人心 2020-12-15 08:18

When I run the following program:

public class Test
{
    public static void main(String[] args)
    {
        System.out.println(args);
    }
{
8条回答
  •  时光取名叫无心
    2020-12-15 08:54

    Update: I just realized I never answered the question "What does “String[] args” contain in java?" :-) It's an array of the command-line arguments provided to the program, each argument being a String in the array.

    And we now resume with our regularly-scheduled answer...

    args is an array. To see individual command-line arguments, index into the array — args[0], args[1], etc.:

    You can loop through the args like this:

    public class Test
    {
        public static void main(String[] args)
        {
            int index;
    
            for (index = 0; index < args.length; ++index)
            {
                System.out.println("args[" + index + "]: " + args[index]);
            }
        }
    }
    

    For java Test one two three, that will output:

    args[0]: one
    args[1]: two
    args[2]: three

    Or loop like this if you don't need the index:

    public class Test
    {
        public static void main(String[] args)
        {
            for (String s : args)
            {
                System.out.println(s);
            }
        }
    }
    

    So, what does "[Ljava.lang.String;@153c375" mean?

    That's Java's default toString return value for String[] (an array of String). See Object#toString. The [ means "array", the L means "class or interface", and java.lang.String is self-explanatory. That part comes from Class#getName(). The ;@153c375 is ;@ followed by the hashCode of the array as a hex string. (I think the default implementation of hashCode for Object indicates where in memory the array is located, which is why it's different for different invocations of your program, but that's unspecified behavior and wouldn't be any use to you anyway.)

提交回复
热议问题