1

This is more of theory question. I have this piece of code:

        String[] contacts = new String[10];

    for (int x = 0; x < contacts.length; x++)
    {
        contacts[x] = "Person" + x;
        System.out.println(contacts[x]);

    }

I understand that arrays can only have one type but I have concatenated the variable x (which is an int) on to the end of the String and stored this into an array. However when I try to do this int based array it doesn't like it which makes sense because you can't mix types in an array that is declared to be holding int variables. Im confused because you can add Boolean as well to the end of the statement.

contacts[x] = "Person" + x + false

As long as the array starts with a String you can get away with it. Is this because the String in an object itself? I'm really sorry if this is an obvious question. I believe this is related to this question but it doesn't quite answer it to my satisfaction Multiple type array

Community
  • 1
  • 1
Izzywizz
  • 21
  • 2
  • 2
    + is a string operator overload. "Person" + `x.ToString()` – Lews Therin Jan 30 '15 at 11:57
  • That's because if the first element is a string, then it calls `toString()` on `x` and it calls `toString()` on the boolean variable. So you'll just get `Person1false`, `Person2false` and so on.` – EpicPandaForce Jan 30 '15 at 11:57
  • You are just adding `String` not `int` neither `boolean` as they are converted to `String`s. – Eypros Jan 30 '15 at 11:58
  • Whenever you concatenate something to a String like this - `String str = "abc" + somOtherThing`, `someOtherThing` is automatically converted to a String by calling `someOtherThing.toString()`, So basically you will have a string. – sarveshseri Jan 30 '15 at 11:59
  • Aww thanks I thought it was that but I wasn't sure, so it essentially converts the value to a string. – Izzywizz Jan 30 '15 at 12:05

2 Answers2

1

That's because if the first element is a string, then it calls toString() on x and it calls toString() on the boolean variable. So you'll just get Person1false, Person2false and so on. And they are all String.

Print them out, you'll see.

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
1

You're not adding multiple types into the array. Like in the following statement, any + operator that follows a string will concatenate the next variable as if it were parsed to a call to toString().

contacts[x] = "Person" + x + false

So the above is the same as;

contacts[x] = "Person" + Objects.toString(x) + Objects.toString(false)

Note that in the above the variables x and the value false are auto-boxed.

Further reading;

Community
  • 1
  • 1
Rudi Kershaw
  • 12,332
  • 7
  • 52
  • 77
  • I didn't realize Java did that conversion automatically so this would be example autoboxing while unboxing would be the reverse – Izzywizz Jan 30 '15 at 12:11