-3
class VarAgs{

    // variable length parameters
    static void vaTest(String ... str){
        System.out.println(str.length + " contains : ");
        for(String s:str){  
            System.out.print(s+" ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        String s1[] = {"hi","hello"};
        vaTest(s1);
        vaTest(s1 + " 1 ");
    }
}

Output:

2 contains : 
hi hello 
1 contains : 
[Ljava.lang.String;@2a139a55 1 
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
Raj Sheth
  • 33
  • 4
  • 1
    Welcome to Stack Overflow. What exception would you expect, and why? Note that in the second call to `vaTest` you're passing a single string, so it's equivalent to `vaTest(new String[] { s1 + " 1 " })` – Jon Skeet Mar 05 '19 at 07:57
  • 1
    Because of arrays return it's type and memory address. – user3756506 Mar 05 '19 at 07:59

3 Answers3

0

When you concatenate an array with a string in

    vaTest(s1 + " 1 ");

Then the reference to the array is converted into a string

 [Ljava.lang.String;@2a139a55

So the method vaTest will receive the

[Ljava.lang.String;@2a139a55 1

as an array with size of 1.

Anil
  • 543
  • 3
  • 16
0

When you do vaTest(s1 + " 1 ");, a string representation of s1 would be used because of string concatenation rules ("+" sign). So instead of a formatted array you get some kind of that: [Ljava.lang.String;@2a139a55

Replace it with vaTest(Arrays.toString(s1) + " 1 "); to get expected result.

amseager
  • 5,795
  • 4
  • 24
  • 47
0

It works as following:

  1. s1 is implicitly converted to String (s1.toString()), this results in [Ljava.lang.String;@2a139a55.
  2. Next, string 1 is added to the above string. This results in [Ljava.lang.String;@2a139a55 1
  3. Next, this resulting string is passed inside single-element array of type String[] into varargs() function.
gudok
  • 4,029
  • 2
  • 20
  • 30