-2

Firstly, I am studying function with new type of signature and body, and in this code, I want to know, what type of object is values? It doesn't appear to be an array of strings based on my observation.
Secondly, is there any method that returns the name of the class a particular object is? I thought it might be tostring, but that returned Ljava.lang.String;@1540e19d in the code below. Don't understand this...

static double AddValues(String ... values) {

    double result = 0;
    Object o = values;
    System.out.println("XXXz");
    System.out.println(o.toString());


    for (String value : values)
    {
        double d = Double.parseDouble(value);
        result += d;

    }

    return result;
}

2 Answers 2

0

This is a varargs argument, and values is treated as a String array. Java is hiding the array creation, note., but you can call that method with an array rather than just a list of arguments.

4
  • I believe L in the descriptor for a reference type means reference; if it were an array, I'd think it would be [Ljava.lang.String.
    – Zymus
    Commented May 27, 2016 at 15:13
  • Yes, you're right re. that Commented May 27, 2016 at 15:20
  • 1
    @Zymus It does return [Ljava.lang.String, even when only one value was supplied to the vararg. OP must have thought the bracket an omission or a useless character.
    – Ordous
    Commented May 27, 2016 at 16:29
  • @Ordous I figured as much. I can't see a way to get that output that OP specified.
    – Zymus
    Commented May 27, 2016 at 16:32
-1

values is an array of String. I'm not sure what observation led you to conclude otherwise. Variadic method parameters in Java collect the arguments into an array, as you can see in the Java 5 varargs documentation.

To find out the type of an object, use values.getClass().getName() (yields "[Ljava.lang.String;" indicating an array of String). You can use values.getClass().isArray() to test whether it is an array and values.getClass().getComponentType() to get the type of its elements.

See the array components documentation for more information.

1
  • Could a downvoter indicate what is wrong with my answer? My answer is correct. The type of values is in fact String[]. Commented Jun 9, 2016 at 10:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.